Created
August 6, 2020 15:27
-
-
Save rednafi/c8f73bb645608db5c691e2b158978c3f to your computer and use it in GitHub Desktop.
Add prefixes before dataclass attributes dynamically
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from dataclasses import dataclass | |
class PrefixMeta(type): | |
def __new__(cls, name, bases, attrs): | |
try: | |
prefix = attrs["Config"].prefix | |
except (KeyError, AttributeError): | |
prefix = None | |
if prefix: | |
for attr_name, attr_value in attrs.items(): | |
conditions = ( | |
isinstance(attr_value, str), | |
attr_value != name, | |
not attr_name.startswith("_"), | |
) | |
if all(conditions): | |
attrs[attr_name] = prefix + attr_value | |
return dataclass(unsafe_hash=True)(super().__new__(cls, name, bases, attrs)) | |
class Prefix(metaclass=PrefixMeta): | |
pass | |
class Foo(Prefix): | |
bar: str = "some_settings" | |
class Config: | |
prefix = "dev_" | |
th = Foo() | |
str(th) == Foo(bar="dev_some_settings") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment