Skip to content

Commit 7f21e1a

Browse files
committed
check the init args only when the given frames are in __init__ method.
1 parent 3bdf8ee commit 7f21e1a

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

src/lightning/pytorch/utilities/parsing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ def get_init_args(frame: types.FrameType) -> dict[str, Any]: # pragma: no-cover
9191

9292
def _get_init_args(frame: types.FrameType) -> tuple[Optional[Any], dict[str, Any]]:
9393
_, _, _, local_vars = inspect.getargvalues(frame)
94-
if "__class__" not in local_vars:
94+
if "__class__" not in local_vars or frame.f_code.co_name != "__init__":
9595
return None, {}
9696
cls = local_vars["__class__"]
9797
init_parameters = inspect.signature(cls.__init__).parameters

tests/tests_pytorch/models/test_hparams.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,20 @@ def __init__(obj, *more_args, other_arg=300, **more_kwargs):
341341
obj.save_hyperparameters()
342342

343343

344+
class _MetaType(type):
345+
def __call__(cls, *args, **kwargs):
346+
instance = super().__call__(*args, **kwargs) # Create the instance
347+
if hasattr(instance, "_after_init"):
348+
instance._after_init(**kwargs) # Call the method if defined
349+
return instance
350+
351+
352+
class MetaTypeBoringModel(CustomBoringModel, metaclass=_MetaType):
353+
def __init__(self, *args, **kwargs):
354+
super().__init__(*args, **kwargs)
355+
self.save_hyperparameters()
356+
357+
344358
if _OMEGACONF_AVAILABLE:
345359

346360
class DictConfSubClassBoringModel(SubClassBoringModel):
@@ -365,6 +379,7 @@ class DictConfSubClassBoringModel: ...
365379
pytest.param(DictConfSubClassBoringModel, marks=RunIf(omegaconf=True)),
366380
BoringModelWithMixin,
367381
BoringModelWithMixinAndInit,
382+
MetaTypeBoringModel,
368383
],
369384
)
370385
def test_collect_init_arguments(tmp_path, cls):

0 commit comments

Comments
 (0)