Python dataclasses.make_dataclass() Examples
The following are 6
code examples of dataclasses.make_dataclass().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
dataclasses
, or try the search function
.
Example #1
Source File: objecttype.py From graphene with MIT License | 6 votes |
def __new__(cls, name_, bases, namespace, **options): # Note: it's safe to pass options as keyword arguments as they are still type-checked by ObjectTypeOptions. # We create this type, to then overload it with the dataclass attrs class InterObjectType: pass base_cls = super().__new__( cls, name_, (InterObjectType,) + bases, namespace, **options, ) if base_cls._meta: fields = [ ( key, "typing.Any", field( default=field_value.default_value if isinstance(field_value, Field) else None ), ) for key, field_value in base_cls._meta.fields.items() ] dataclass = make_dataclass(name_, fields, bases=()) InterObjectType.__init__ = dataclass.__init__ InterObjectType.__eq__ = dataclass.__eq__ InterObjectType.__repr__ = dataclass.__repr__ return base_cls
Example #2
Source File: utils.py From pycon with MIT License | 5 votes |
def create_input_type(base_name, graphql_fields): input_class = dataclasses.make_dataclass( f"{base_name}Input", [(name, type_, field) for name, [type_, field] in graphql_fields.items()], ) return strawberry.input(input_class)
Example #3
Source File: utils.py From pycon with MIT License | 5 votes |
def create_error_type(base_name, graphql_fields): fields = [ (name, List[str], dataclasses.field(default_factory=list)) for name, _ in graphql_fields.items() ] fields.append( ("nonFieldErrors", List[str], dataclasses.field(default_factory=list)) ) error_type = dataclasses.make_dataclass(f"{base_name}Errors", fields) return strawberry.type(error_type)
Example #4
Source File: base.py From dffml with MIT License | 5 votes |
def make_config(cls_name: str, fields, *args, namespace=None, **kwargs): """ Function to create a dataclass """ if namespace is None: namespace = {} namespace.setdefault("_fromdict", classmethod(_fromdict)) namespace.setdefault( "_replace", lambda self, *args, **kwargs: dataclasses.replace( self, *args, **kwargs ), ) namespace.setdefault("_asdict", config_asdict) kwargs["eq"] = True kwargs["init"] = True # Ensure non-default arguments always come before default arguments fields_non_default = [] fields_default = [] for name, cls, field in fields: if ( field.default is not dataclasses.MISSING or field.default_factory is not dataclasses.MISSING ): fields_default.append((name, cls, field)) else: fields_non_default.append((name, cls, field)) fields = fields_non_default + fields_default # Create dataclass return dataclasses.make_dataclass( cls_name, fields, *args, namespace=namespace, **kwargs )
Example #5
Source File: style_transfer.py From style_transfer with MIT License | 5 votes |
def make_msg_type(cls_name, fields): """Makes dataclass-based message types for IPC.""" if isinstance(fields, str): fields = fields.split() return make_dataclass(cls_name, fields, namespace={'__module__': __name__})
Example #6
Source File: flows.py From spins-b with GNU General Public License v3.0 | 4 votes |
def __new__(meta, name, bases, class_dict): cls = type.__new__(meta, name, bases, class_dict) cls = dataclasses.dataclass(cls, eq=False) # Get the fields for inner class autogeneration. cls_fields = dataclasses.fields(cls) # Keep track of all the fields that can vary. nonconst_fields = [] for field in cls_fields: if ("constant_field" in field.metadata) and ( field.metadata["constant_field"]): continue nonconst_fields.append(field) # Create constant flag class. if "ConstFlags" not in cls.__dict__: const_flag_fields = [(field.name, bool, dataclasses.field(default=False)) for field in nonconst_fields] cls.ConstFlags = dataclasses.make_dataclass(name + ".ConstFlags", const_flag_fields) def __bool__(self) -> bool: return all( getattr(self, field.name) for field in nonconst_fields) def set_all(self, value: bool) -> None: for field in nonconst_fields: setattr(self, field.name, value) cls.ConstFlags.__bool__ = __bool__ cls.ConstFlags.set_all = set_all # Create the gradient class. if "Grad" not in cls.__dict__: grad_fields = [(field.name + "_grad", field.type, np_zero_field(1)) for field in nonconst_fields] grad_bases = tuple(cls_base.Grad for cls_base in bases) cls.Grad = dataclasses.make_dataclass(name + ".Grad", grad_fields, bases=grad_bases) def __iadd__(self, value): for field in grad_fields: field_val = getattr(self, field[0]) value_val = getattr(value, field[0]) try: field_val.__iadd__(value_val) except AttributeError: setattr(self, field[0], value_val + field_val) return super(cls.Grad, self).__iadd__(value) cls.Grad.__iadd__ = __iadd__ return cls