Created
October 11, 2019 07:50
-
-
Save Reflexe/0e58f9f8efbb21a1e48bbda3d96fa341 to your computer and use it in GitHub Desktop.
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 | |
def dataclass_with_default_init(_cls=None, *args, **kwargs): | |
def wrap(cls): | |
# Save the current __init__ and remove it so dataclass will | |
# create the default __init__. | |
user_init = getattr(cls, "__init__") | |
delattr(cls, "__init__") | |
# let dataclass process our class. | |
result = dataclass(cls, *args, **kwargs) | |
# Restore the user's __init__ save the default init to __default_init__. | |
setattr(result, "__default_init__", result.__init__) | |
setattr(result, "__init__", user_init) | |
# Just in case that dataclass will return a new instance, | |
# (currently, does not happen), restore cls's __init__. | |
if result is not cls: | |
setattr(cls, "__init__", user_init) | |
return result | |
# Support both dataclass_with_default_init() and dataclass_with_default_init | |
if _cls is None: | |
return wrap | |
else: | |
return wrap(_cls) | |
@dataclass_with_default_init(frozen=True) | |
class DataClass: | |
value: int | |
def __init__(self, value: str): | |
# error: | |
# self.value = int(value) | |
self.__default_init__(value=int(value)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment