Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature Request] Self-referencing _target_ #2272

Closed
Laleee opened this issue Jun 22, 2022 · 2 comments
Closed

[Feature Request] Self-referencing _target_ #2272

Laleee opened this issue Jun 22, 2022 · 2 comments
Labels
enhancement Enhanvement request

Comments

@Laleee
Copy link

Laleee commented Jun 22, 2022

馃殌 Feature Request

Defining default value for target which will refer to the same class.

Motivation

I have a lot of classes whose target is self. It would be fantastic if target could have some keyword that could suggest that the target is that same class.

Pitch

@dataclass
class SomeDataClass:
    attr1: str
    attr2: str
    att3: int
    _target_: str = 'path.to.the.file.SomeDataClas'

Additional context

I guess it's possible to automatically extract the class path relative to the project's root.

@Laleee Laleee added the enhancement Enhanvement request label Jun 22, 2022
@Jasha10
Copy link
Collaborator

Jasha10 commented Jun 22, 2022

I think you can get away with using the module's __name__ attribute for this:

@dataclass
class SomeDataClass:
    attr1: str
    attr2: str
    att3: int
    _target_: str = __name__ + ".SomeDataClass"

or even:

@dataclass
class SomeDataClass:
    attr1: str
    attr2: str
    att3: int
    _target_: str = f"{__name__}.{__qualname__}"  # path to Self

An alternative would be to skip defining the _target_ field and use OmegaConf.to_object:

from dataclasses import dataclass
from omegaconf import OmegaConf

@dataclass
class SomeDataClass:
    attr1: str
    attr2: str
    att3: int

cfg = OmegaConf.create(SomeDataClass("foo", "bar", 123))

instance = OmegaConf.to_object(cfg)
assert isinstance(instance, SomeDataClass)
assert instance.attr1 == "foo"

See issue #1719 for caveats regarding the combination of hydra.utils.instantiate with OmegaConf.to_object.

@Laleee
Copy link
Author

Laleee commented Jun 23, 2022

The second solution is great! Thanks a lot Jasha!

I think that 3. solution woudn't work when attributes are more complex (I'd have to mess with OmegaConfig's allow_objects).

@Laleee Laleee closed this as completed Jun 23, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement Enhanvement request
Projects
None yet
Development

No branches or pull requests

2 participants