Skip to content

Instantly share code, notes, and snippets.

@rednafi
Created August 6, 2020 15:27
Show Gist options
  • Save rednafi/c8f73bb645608db5c691e2b158978c3f to your computer and use it in GitHub Desktop.
Save rednafi/c8f73bb645608db5c691e2b158978c3f to your computer and use it in GitHub Desktop.
Add prefixes before dataclass attributes dynamically
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