Last active
May 21, 2021 02:41
-
-
Save a-recknagel/7b4b869bfba460535c85b9c4e0ef789d to your computer and use it in GitHub Desktop.
typed_property with default and default_factory
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 typing import Any, Union, Callable | |
SENTINEL = object() | |
def typed_property( | |
name: str, | |
default: Any = SENTINEL, | |
default_factory: Union[Callable, SENTINEL] = SENTINEL | |
): | |
if default is SENTINEL and default_factory is SENTINEL: | |
raise TypeError("Choose to use either default or its factory, not both!") | |
elif default is SENTINEL: | |
default = default_factory() | |
else: | |
default = None | |
varname = "_" + name | |
@property | |
def prop(self): | |
if not hasattr(self, varname): | |
setattr(self, varname, default) | |
return getattr(self, varname) | |
@prop.setter | |
def setter(self, value): | |
setattr(self, varname, value) | |
return prop | |
class MyClass: | |
data = typed_property("data", default_factory=dict) | |
class MyOtherClass: | |
data = typed_property("data", default={1: 1}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment