Как узнать число полей у dataclass класса

от admin

How to get number of attributes in a dataclass? [closed]

I want to get the number of recipes I have in the Recipes class. How do I go about doing this?

This is what I have so far. I want the thing at the end to print the number of recipes in the class (currently being 2).

Edit: I can’t use dict or lists because this is just a test for something I am working on.

2 Answers 2

You can traverse Recipes.__dict__ to count all entries of type Recipe . This dict contains all set attributes and few other entries.

The thing I am confused about is you mentioned you don’t want to work with dict objects, yet a class __dict__ is a mappingproxy type object — which you can determine for ex. using type(Recipe.__dict__) — which I’d argue is technically a dict type.

The below alternate solution does not use a class level __dict__ to store the Recipies at all, rather it uses a function locals() object to store it, just to draw a parallel between this and __dict__ , which I feel are very similar in that regards.

But if you wanted to be really clever, you could also get by with using __dict__ and setattr as originally desired, without using a separate class at all! Here’s an example of substituting a function instead of a class for this same purpose:

dataclasses — Data Classes¶

This module provides a decorator and functions for automatically adding generated special method s such as __init__() and __repr__() to user-defined classes. It was originally described in PEP 557.

The member variables to use in these generated methods are defined using PEP 526 type annotations. For example, this code:

will add, among other things, a __init__() that looks like:

Note that this method is automatically added to the class: it is not directly specified in the InventoryItem definition shown above.

New in version 3.7.

Module contents¶

This function is a decorator that is used to add generated special method s to classes, as described below.

The dataclass() decorator examines the class to find field s. A field is defined as a class variable that has a type annotation . With two exceptions described below, nothing in dataclass() examines the type specified in the variable annotation.

The order of the fields in all of the generated methods is the order in which they appear in the class definition.

The dataclass() decorator will add various “dunder” methods to the class, described below. If any of the added methods already exist in the class, the behavior depends on the parameter, as documented below. The decorator returns the same class that it is called on; no new class is created.

If dataclass() is used just as a simple decorator with no parameters, it acts as if it has the default values documented in this signature. That is, these three uses of dataclass() are equivalent:

The parameters to dataclass() are:

init : If true (the default), a __init__() method will be generated.

If the class already defines __init__() , this parameter is ignored.

repr : If true (the default), a __repr__() method will be generated. The generated repr string will have the class name and the name and repr of each field, in the order they are defined in the class. Fields that are marked as being excluded from the repr are not included. For example: InventoryItem(name=’widget’, unit_price=3.0, quantity_on_hand=10) .

If the class already defines __repr__() , this parameter is ignored.

eq : If true (the default), an __eq__() method will be generated. This method compares the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type.

If the class already defines __eq__() , this parameter is ignored.

order : If true (the default is False ), __lt__() , __le__() , __gt__() , and __ge__() methods will be generated. These compare the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type. If order is true and eq is false, a ValueError is raised.

If the class already defines any of __lt__() , __le__() , __gt__() , or __ge__() , then TypeError is raised.

unsafe_hash : If False (the default), a __hash__() method is generated according to how eq and frozen are set.

__hash__() is used by built-in hash() , and when objects are added to hashed collections such as dictionaries and sets. Having a __hash__() implies that instances of the class are immutable. Mutability is a complicated property that depends on the programmer’s intent, the existence and behavior of __eq__() , and the values of the eq and frozen flags in the dataclass() decorator.

By default, dataclass() will not implicitly add a __hash__() method unless it is safe to do so. Neither will it add or change an existing explicitly defined __hash__() method. Setting the class attribute __hash__ = None has a specific meaning to Python, as described in the __hash__() documentation.

If __hash__() is not explicitly defined, or if it is set to None , then dataclass() may add an implicit __hash__() method. Although not recommended, you can force dataclass() to create a __hash__() method with unsafe_hash=True . This might be the case if your class is logically immutable but can nonetheless be mutated. This is a specialized use case and should be considered carefully.

Here are the rules governing implicit creation of a __hash__() method. Note that you cannot both have an explicit __hash__() method in your dataclass and set unsafe_hash=True ; this will result in a TypeError .

If eq and frozen are both true, by default dataclass() will generate a __hash__() method for you. If eq is true and frozen is false, __hash__() will be set to None , marking it unhashable (which it is, since it is mutable). If eq is false, __hash__() will be left untouched meaning the __hash__() method of the superclass will be used (if the superclass is object , this means it will fall back to id-based hashing).

frozen : If true (the default is False ), assigning to fields will generate an exception. This emulates read-only frozen instances. If __setattr__() or __delattr__() is defined in the class, then TypeError is raised. See the discussion below.

match_args : If true (the default is True ), the __match_args__ tuple will be created from the list of parameters to the generated __init__() method (even if __init__() is not generated, see above). If false, or if __match_args__ is already defined in the class, then __match_args__ will not be generated.

New in version 3.10.

kw_only : If true (the default value is False ), then all fields will be marked as keyword-only. If a field is marked as keyword-only, then the only effect is that the __init__() parameter generated from a keyword-only field must be specified with a keyword when __init__() is called. There is no effect on any other aspect of dataclasses. See the parameter glossary entry for details. Also see the KW_ONLY section.

New in version 3.10.

slots : If true (the default is False ), __slots__ attribute will be generated and new class will be returned instead of the original one. If __slots__ is already defined in the class, then TypeError is raised.

New in version 3.10.

Changed in version 3.11: If a field name is already included in the __slots__ of a base class, it will not be included in the generated __slots__ to prevent overriding them . Therefore, do not use __slots__ to retrieve the field names of a dataclass. Use fields() instead. To be able to determine inherited slots, base class __slots__ may be any iterable, but not an iterator.

weakref_slot : If true (the default is False ), add a slot named “__weakref__”, which is required to make an instance weakref-able. It is an error to specify weakref_slot=True without also specifying slots=True .

New in version 3.11.

field s may optionally specify a default value, using normal Python syntax:

In this example, both a and b will be included in the added __init__() method, which will be defined as:

TypeError will be raised if a field without a default value follows a field with a default value. This is true whether this occurs in a single class, or as a result of class inheritance.

dataclasses. field ( * , default = MISSING , default_factory = MISSING , init = True , repr = True , hash = None , compare = True , metadata = None , kw_only = MISSING ) ¶

For common and simple use cases, no other functionality is required. There are, however, some dataclass features that require additional per-field information. To satisfy this need for additional information, you can replace the default field value with a call to the provided field() function. For example:

As shown above, the MISSING value is a sentinel object used to detect if some parameters are provided by the user. This sentinel is used because None is a valid value for some parameters with a distinct meaning. No code should directly use the MISSING value.

The parameters to field() are:

default : If provided, this will be the default value for this field. This is needed because the field() call itself replaces the normal position of the default value.

default_factory : If provided, it must be a zero-argument callable that will be called when a default value is needed for this field. Among other purposes, this can be used to specify fields with mutable default values, as discussed below. It is an error to specify both default and default_factory .

init : If true (the default), this field is included as a parameter to the generated __init__() method.

repr : If true (the default), this field is included in the string returned by the generated __repr__() method.

hash : This can be a bool or None . If true, this field is included in the generated __hash__() method. If None (the default), use the value of compare : this would normally be the expected behavior. A field should be considered in the hash if it’s used for comparisons. Setting this value to anything other than None is discouraged.

One possible reason to set hash=False but compare=True would be if a field is expensive to compute a hash value for, that field is needed for equality testing, and there are other fields that contribute to the type’s hash value. Even if a field is excluded from the hash, it will still be used for comparisons.

compare : If true (the default), this field is included in the generated equality and comparison methods ( __eq__() , __gt__() , et al.).

metadata : This can be a mapping or None. None is treated as an empty dict. This value is wrapped in MappingProxyType() to make it read-only, and exposed on the Field object. It is not used at all by Data Classes, and is provided as a third-party extension mechanism. Multiple third-parties can each have their own key, to use as a namespace in the metadata.

kw_only : If true, this field will be marked as keyword-only. This is used when the generated __init__() method’s parameters are computed.

New in version 3.10.

If the default value of a field is specified by a call to field() , then the class attribute for this field will be replaced by the specified default value. If no default is provided, then the class attribute will be deleted. The intent is that after the dataclass() decorator runs, the class attributes will all contain the default values for the fields, just as if the default value itself were specified. For example, after:

The class attribute C.z will be 10 , the class attribute C.t will be 20 , and the class attributes C.x and C.y will not be set.

class dataclasses. Field ¶

Field objects describe each defined field. These objects are created internally, and are returned by the fields() module-level method (see below). Users should never instantiate a Field object directly. Its documented attributes are:

  • name : The name of the field.

  • type : The type of the field.

  • default , default_factory , init , repr , hash , compare , metadata , and kw_only have the identical meaning and values as they do in the field() function.

Other attributes may exist, but they are private and must not be inspected or relied on.

dataclasses. fields ( class_or_instance ) ¶

Returns a tuple of Field objects that define the fields for this dataclass. Accepts either a dataclass, or an instance of a dataclass. Raises TypeError if not passed a dataclass or instance of one. Does not return pseudo-fields which are ClassVar or InitVar .

dataclasses. asdict ( obj , * , dict_factory = dict ) ¶

Converts the dataclass obj to a dict (by using the factory function dict_factory ). Each dataclass is converted to a dict of its fields, as name: value pairs. dataclasses, dicts, lists, and tuples are recursed into. Other objects are copied with copy.deepcopy() .

Example of using asdict() on nested dataclasses:

To create a shallow copy, the following workaround may be used:

asdict() raises TypeError if obj is not a dataclass instance.

dataclasses. astuple ( obj , * , tuple_factory = tuple ) ¶

Converts the dataclass obj to a tuple (by using the factory function tuple_factory ). Each dataclass is converted to a tuple of its field values. dataclasses, dicts, lists, and tuples are recursed into. Other objects are copied with copy.deepcopy() .

Continuing from the previous example:

To create a shallow copy, the following workaround may be used:

astuple() raises TypeError if obj is not a dataclass instance.

dataclasses. make_dataclass ( cls_name , fields , * , bases = () , namespace = None , init = True , repr = True , eq = True , order = False , unsafe_hash = False , frozen = False , match_args = True , kw_only = False , slots = False , weakref_slot = False ) ¶

Creates a new dataclass with name cls_name , fields as defined in fields , base classes as given in bases , and initialized with a namespace as given in namespace . fields is an iterable whose elements are each either name , (name, type) , or (name, type, Field) . If just name is supplied, typing.Any is used for type . The values of init , repr , eq , order , unsafe_hash , frozen , match_args , kw_only , slots , and weakref_slot have the same meaning as they do in dataclass() .

This function is not strictly required, because any Python mechanism for creating a new class with __annotations__ can then apply the dataclass() function to convert that class to a dataclass. This function is provided as a convenience. For example:

Is equivalent to:

Creates a new object of the same type as obj , replacing fields with values from changes . If obj is not a Data Class, raises TypeError . If values in changes do not specify fields, raises TypeError .

The newly returned object is created by calling the __init__() method of the dataclass. This ensures that __post_init__() , if present, is also called.

Init-only variables without default values, if any exist, must be specified on the call to replace() so that they can be passed to __init__() and __post_init__() .

It is an error for changes to contain any fields that are defined as having init=False . A ValueError will be raised in this case.

Be forewarned about how init=False fields work during a call to replace() . They are not copied from the source object, but rather are initialized in __post_init__() , if they’re initialized at all. It is expected that init=False fields will be rarely and judiciously used. If they are used, it might be wise to have alternate class constructors, or perhaps a custom replace() (or similarly named) method which handles instance copying.

dataclasses. is_dataclass ( obj ) ¶

Return True if its parameter is a dataclass or an instance of one, otherwise return False .

If you need to know if a class is an instance of a dataclass (and not a dataclass itself), then add a further check for not isinstance(obj, type) :

A sentinel value signifying a missing default or default_factory.

A sentinel value used as a type annotation. Any fields after a pseudo-field with the type of KW_ONLY are marked as keyword-only fields. Note that a pseudo-field of type KW_ONLY is otherwise completely ignored. This includes the name of such a field. By convention, a name of _ is used for a KW_ONLY field. Keyword-only fields signify __init__() parameters that must be specified as keywords when the class is instantiated.

In this example, the fields y and z will be marked as keyword-only fields:

In a single dataclass, it is an error to specify more than one field whose type is KW_ONLY .

New in version 3.10.

Raised when an implicitly defined __setattr__() or __delattr__() is called on a dataclass which was defined with frozen=True . It is a subclass of AttributeError .

Post-init processing¶

The generated __init__() code will call a method named __post_init__() , if __post_init__() is defined on the class. It will normally be called as self.__post_init__() . However, if any InitVar fields are defined, they will also be passed to __post_init__() in the order they were defined in the class. If no __init__() method is generated, then __post_init__() will not automatically be called.

Among other uses, this allows for initializing field values that depend on one or more other fields. For example:

The __init__() method generated by dataclass() does not call base class __init__() methods. If the base class has an __init__() method that has to be called, it is common to call this method in a __post_init__() method:

Note, however, that in general the dataclass-generated __init__() methods don’t need to be called, since the derived dataclass will take care of initializing all fields of any base class that is a dataclass itself.

See the section below on init-only variables for ways to pass parameters to __post_init__() . Also see the warning about how replace() handles init=False fields.

Class variables¶

One of the few places where dataclass() actually inspects the type of a field is to determine if a field is a class variable as defined in PEP 526. It does this by checking if the type of the field is typing.ClassVar . If a field is a ClassVar , it is excluded from consideration as a field and is ignored by the dataclass mechanisms. Such ClassVar pseudo-fields are not returned by the module-level fields() function.

Init-only variables¶

Another place where dataclass() inspects a type annotation is to determine if a field is an init-only variable. It does this by seeing if the type of a field is of type dataclasses.InitVar . If a field is an InitVar , it is considered a pseudo-field called an init-only field. As it is not a true field, it is not returned by the module-level fields() function. Init-only fields are added as parameters to the generated __init__() method, and are passed to the optional __post_init__() method. They are not otherwise used by dataclasses.

For example, suppose a field will be initialized from a database, if a value is not provided when creating the class:

In this case, fields() will return Field objects for i and j , but not for database .

Frozen instances¶

It is not possible to create truly immutable Python objects. However, by passing frozen=True to the dataclass() decorator you can emulate immutability. In that case, dataclasses will add __setattr__() and __delattr__() methods to the class. These methods will raise a FrozenInstanceError when invoked.

There is a tiny performance penalty when using frozen=True : __init__() cannot use simple assignment to initialize fields, and must use object.__setattr__() .

Inheritance¶

When the dataclass is being created by the dataclass() decorator, it looks through all of the class’s base classes in reverse MRO (that is, starting at object ) and, for each dataclass that it finds, adds the fields from that base class to an ordered mapping of fields. After all of the base class fields are added, it adds its own fields to the ordered mapping. All of the generated methods will use this combined, calculated ordered mapping of fields. Because the fields are in insertion order, derived classes override base classes. An example:

The final list of fields is, in order, x , y , z . The final type of x is int , as specified in class C .

The generated __init__() method for C will look like:

Re-ordering of keyword-only parameters in __init__() ¶

After the parameters needed for __init__() are computed, any keyword-only parameters are moved to come after all regular (non-keyword-only) parameters. This is a requirement of how keyword-only parameters are implemented in Python: they must come after non-keyword-only parameters.

In this example, Base.y , Base.w , and D.t are keyword-only fields, and Base.x and D.z are regular fields:

The generated __init__() method for D will look like:

Note that the parameters have been re-ordered from how they appear in the list of fields: parameters derived from regular fields are followed by parameters derived from keyword-only fields.

The relative ordering of keyword-only parameters is maintained in the re-ordered __init__() parameter list.

Default factory functions¶

If a field() specifies a default_factory , it is called with zero arguments when a default value for the field is needed. For example, to create a new instance of a list, use:

If a field is excluded from __init__() (using init=False ) and the field also specifies default_factory , then the default factory function will always be called from the generated __init__() function. This happens because there is no other way to give the field an initial value.

Mutable default values¶

Python stores default member variable values in class attributes. Consider this example, not using dataclasses:

Note that the two instances of class C share the same class variable x , as expected.

Using dataclasses, if this code was valid:

it would generate code similar to:

This has the same issue as the original example using class C . That is, two instances of class D that do not specify a value for x when creating a class instance will share the same copy of x . Because dataclasses just use normal Python class creation they also share this behavior. There is no general way for Data Classes to detect this condition. Instead, the dataclass() decorator will raise a TypeError if it detects an unhashable default parameter. The assumption is that if a value is unhashable, it is mutable. This is a partial solution, but it does protect against many common errors.

Using default factory functions is a way to create new instances of mutable types as default values for fields:

Changed in version 3.11: Instead of looking for and disallowing objects of type list , dict , or set , unhashable objects are now not allowed as default values. Unhashability is used to approximate mutability.

Descriptor-typed fields¶

Fields that are assigned descriptor objects as their default value have the following special behaviors:

The value for the field passed to the dataclass’s __init__ method is passed to the descriptor’s __set__ method rather than overwriting the descriptor object.

Similarly, when getting or setting the field, the descriptor’s __get__ or __set__ method is called rather than returning or overwriting the descriptor object.

To determine whether a field contains a default value, dataclasses will call the descriptor’s __get__ method using its class access form (i.e. descriptor.__get__(obj=None, type=cls) . If the descriptor returns a value in this case, it will be used as the field’s default. On the other hand, if the descriptor raises AttributeError in this situation, no default value will be provided for the field.

Note that if a field is annotated with a descriptor type, but is not assigned a descriptor object as its default value, the field will act like a normal field.

Как узнать число полей у dataclass класса

This module provides a decorator and functions for automatically adding generated special method s such as __init__() and __repr__() to user-defined classes. It was originally described in PEP 557.

The member variables to use in these generated methods are defined using PEP 526 type annotations. For example, this code:

will add, among other things, a __init__() that looks like:

Note that this method is automatically added to the class: it is not directly specified in the InventoryItem definition shown above.

New in version 3.7.

Module contents¶

This function is a decorator that is used to add generated special method s to classes, as described below.

The dataclass() decorator examines the class to find field s. A field is defined as a class variable that has a type annotation . With two exceptions described below, nothing in dataclass() examines the type specified in the variable annotation.

The order of the fields in all of the generated methods is the order in which they appear in the class definition.

The dataclass() decorator will add various “dunder” methods to the class, described below. If any of the added methods already exist in the class, the behavior depends on the parameter, as documented below. The decorator returns the same class that it is called on; no new class is created.

If dataclass() is used just as a simple decorator with no parameters, it acts as if it has the default values documented in this signature. That is, these three uses of dataclass() are equivalent:

The parameters to dataclass() are:

init : If true (the default), a __init__() method will be generated.

If the class already defines __init__() , this parameter is ignored.

repr : If true (the default), a __repr__() method will be generated. The generated repr string will have the class name and the name and repr of each field, in the order they are defined in the class. Fields that are marked as being excluded from the repr are not included. For example: InventoryItem(name=’widget’, unit_price=3.0, quantity_on_hand=10) .

If the class already defines __repr__() , this parameter is ignored.

eq : If true (the default), an __eq__() method will be generated. This method compares the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type.

If the class already defines __eq__() , this parameter is ignored.

order : If true (the default is False ), __lt__() , __le__() , __gt__() , and __ge__() methods will be generated. These compare the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type. If order is true and eq is false, a ValueError is raised.

If the class already defines any of __lt__() , __le__() , __gt__() , or __ge__() , then TypeError is raised.

unsafe_hash : If False (the default), a __hash__() method is generated according to how eq and frozen are set.

__hash__() is used by built-in hash() , and when objects are added to hashed collections such as dictionaries and sets. Having a __hash__() implies that instances of the class are immutable. Mutability is a complicated property that depends on the programmer’s intent, the existence and behavior of __eq__() , and the values of the eq and frozen flags in the dataclass() decorator.

By default, dataclass() will not implicitly add a __hash__() method unless it is safe to do so. Neither will it add or change an existing explicitly defined __hash__() method. Setting the class attribute __hash__ = None has a specific meaning to Python, as described in the __hash__() documentation.

If __hash__() is not explicitly defined, or if it is set to None , then dataclass() may add an implicit __hash__() method. Although not recommended, you can force dataclass() to create a __hash__() method with unsafe_hash=True . This might be the case if your class is logically immutable but can nonetheless be mutated. This is a specialized use case and should be considered carefully.

Here are the rules governing implicit creation of a __hash__() method. Note that you cannot both have an explicit __hash__() method in your dataclass and set unsafe_hash=True ; this will result in a TypeError .

If eq and frozen are both true, by default dataclass() will generate a __hash__() method for you. If eq is true and frozen is false, __hash__() will be set to None , marking it unhashable (which it is, since it is mutable). If eq is false, __hash__() will be left untouched meaning the __hash__() method of the superclass will be used (if the superclass is object , this means it will fall back to id-based hashing).

Читать:
Cheat engine как найти нужное значение

frozen : If true (the default is False ), assigning to fields will generate an exception. This emulates read-only frozen instances. If __setattr__() or __delattr__() is defined in the class, then TypeError is raised. See the discussion below.

match_args : If true (the default is True ), the __match_args__ tuple will be created from the list of parameters to the generated __init__() method (even if __init__() is not generated, see above). If false, or if __match_args__ is already defined in the class, then __match_args__ will not be generated.

New in version 3.10.

kw_only : If true (the default value is False ), then all fields will be marked as keyword-only. If a field is marked as keyword-only, then the only affect is that the __init__() parameter generated from a keyword-only field must be specified with a keyword when __init__() is called. There is no effect on any other aspect of dataclasses. See the parameter glossary entry for details. Also see the KW_ONLY section.

New in version 3.10.

slots : If true (the default is False ), __slots__ attribute will be generated and new class will be returned instead of the original one. If __slots__ is already defined in the class, then TypeError is raised.

New in version 3.10.

field s may optionally specify a default value, using normal Python syntax:

In this example, both a and b will be included in the added __init__() method, which will be defined as:

TypeError will be raised if a field without a default value follows a field with a default value. This is true whether this occurs in a single class, or as a result of class inheritance.

dataclasses. field ( * , default = MISSING , default_factory = MISSING , init = True , repr = True , hash = None , compare = True , metadata = None , kw_only = MISSING ) ¶

For common and simple use cases, no other functionality is required. There are, however, some dataclass features that require additional per-field information. To satisfy this need for additional information, you can replace the default field value with a call to the provided field() function. For example:

As shown above, the MISSING value is a sentinel object used to detect if some parameters are provided by the user. This sentinel is used because None is a valid value for some parameters with a distinct meaning. No code should directly use the MISSING value.

The parameters to field() are:

default : If provided, this will be the default value for this field. This is needed because the field() call itself replaces the normal position of the default value.

default_factory : If provided, it must be a zero-argument callable that will be called when a default value is needed for this field. Among other purposes, this can be used to specify fields with mutable default values, as discussed below. It is an error to specify both default and default_factory .

init : If true (the default), this field is included as a parameter to the generated __init__() method.

repr : If true (the default), this field is included in the string returned by the generated __repr__() method.

hash : This can be a bool or None . If true, this field is included in the generated __hash__() method. If None (the default), use the value of compare : this would normally be the expected behavior. A field should be considered in the hash if it’s used for comparisons. Setting this value to anything other than None is discouraged.

One possible reason to set hash=False but compare=True would be if a field is expensive to compute a hash value for, that field is needed for equality testing, and there are other fields that contribute to the type’s hash value. Even if a field is excluded from the hash, it will still be used for comparisons.

compare : If true (the default), this field is included in the generated equality and comparison methods ( __eq__() , __gt__() , et al.).

metadata : This can be a mapping or None. None is treated as an empty dict. This value is wrapped in MappingProxyType() to make it read-only, and exposed on the Field object. It is not used at all by Data Classes, and is provided as a third-party extension mechanism. Multiple third-parties can each have their own key, to use as a namespace in the metadata.

kw_only : If true, this field will be marked as keyword-only. This is used when the generated __init__() method’s parameters are computed.

New in version 3.10.

If the default value of a field is specified by a call to field() , then the class attribute for this field will be replaced by the specified default value. If no default is provided, then the class attribute will be deleted. The intent is that after the dataclass() decorator runs, the class attributes will all contain the default values for the fields, just as if the default value itself were specified. For example, after:

The class attribute C.z will be 10 , the class attribute C.t will be 20 , and the class attributes C.x and C.y will not be set.

class dataclasses. Field ¶

Field objects describe each defined field. These objects are created internally, and are returned by the fields() module-level method (see below). Users should never instantiate a Field object directly. Its documented attributes are:

name : The name of the field.

type : The type of the field.

default , default_factory , init , repr , hash , compare , metadata , and kw_only have the identical meaning and values as they do in the field() function.

Other attributes may exist, but they are private and must not be inspected or relied on.

dataclasses. fields ( class_or_instance ) ¶

Returns a tuple of Field objects that define the fields for this dataclass. Accepts either a dataclass, or an instance of a dataclass. Raises TypeError if not passed a dataclass or instance of one. Does not return pseudo-fields which are ClassVar or InitVar .

dataclasses. asdict ( obj , * , dict_factory = dict ) ¶

Converts the dataclass obj to a dict (by using the factory function dict_factory ). Each dataclass is converted to a dict of its fields, as name: value pairs. dataclasses, dicts, lists, and tuples are recursed into. Other objects are copied with copy.deepcopy() .

Example of using asdict() on nested dataclasses:

To create a shallow copy, the following workaround may be used:

asdict() raises TypeError if obj is not a dataclass instance.

dataclasses. astuple ( obj , * , tuple_factory = tuple ) ¶

Converts the dataclass obj to a tuple (by using the factory function tuple_factory ). Each dataclass is converted to a tuple of its field values. dataclasses, dicts, lists, and tuples are recursed into. Other objects are copied with copy.deepcopy() .

Continuing from the previous example:

To create a shallow copy, the following workaround may be used:

astuple() raises TypeError if obj is not a dataclass instance.

dataclasses. make_dataclass ( cls_name , fields , * , bases = () , namespace = None , init = True , repr = True , eq = True , order = False , unsafe_hash = False , frozen = False , match_args = True , kw_only = False , slots = False ) ¶

Creates a new dataclass with name cls_name , fields as defined in fields , base classes as given in bases , and initialized with a namespace as given in namespace . fields is an iterable whose elements are each either name , (name, type) , or (name, type, Field) . If just name is supplied, typing.Any is used for type . The values of init , repr , eq , order , unsafe_hash , frozen , match_args , kw_only , and slots have the same meaning as they do in dataclass() .

This function is not strictly required, because any Python mechanism for creating a new class with __annotations__ can then apply the dataclass() function to convert that class to a dataclass. This function is provided as a convenience. For example:

Is equivalent to:

Creates a new object of the same type as obj , replacing fields with values from changes . If obj is not a Data Class, raises TypeError . If values in changes do not specify fields, raises TypeError .

The newly returned object is created by calling the __init__() method of the dataclass. This ensures that __post_init__() , if present, is also called.

Init-only variables without default values, if any exist, must be specified on the call to replace() so that they can be passed to __init__() and __post_init__() .

It is an error for changes to contain any fields that are defined as having init=False . A ValueError will be raised in this case.

Be forewarned about how init=False fields work during a call to replace() . They are not copied from the source object, but rather are initialized in __post_init__() , if they’re initialized at all. It is expected that init=False fields will be rarely and judiciously used. If they are used, it might be wise to have alternate class constructors, or perhaps a custom replace() (or similarly named) method which handles instance copying.

dataclasses. is_dataclass ( obj ) ¶

Return True if its parameter is a dataclass or an instance of one, otherwise return False .

If you need to know if a class is an instance of a dataclass (and not a dataclass itself), then add a further check for not isinstance(obj, type) :

A sentinel value signifying a missing default or default_factory.

A sentinel value used as a type annotation. Any fields after a pseudo-field with the type of KW_ONLY are marked as keyword-only fields. Note that a pseudo-field of type KW_ONLY is otherwise completely ignored. This includes the name of such a field. By convention, a name of _ is used for a KW_ONLY field. Keyword-only fields signify __init__() parameters that must be specified as keywords when the class is instantiated.

In this example, the fields y and z will be marked as keyword-only fields:

In a single dataclass, it is an error to specify more than one field whose type is KW_ONLY .

New in version 3.10.

Raised when an implicitly defined __setattr__() or __delattr__() is called on a dataclass which was defined with frozen=True . It is a subclass of AttributeError .

Post-init processing¶

The generated __init__() code will call a method named __post_init__() , if __post_init__() is defined on the class. It will normally be called as self.__post_init__() . However, if any InitVar fields are defined, they will also be passed to __post_init__() in the order they were defined in the class. If no __init__() method is generated, then __post_init__() will not automatically be called.

Among other uses, this allows for initializing field values that depend on one or more other fields. For example:

The __init__() method generated by dataclass() does not call base class __init__() methods. If the base class has an __init__() method that has to be called, it is common to call this method in a __post_init__() method:

Note, however, that in general the dataclass-generated __init__() methods don’t need to be called, since the derived dataclass will take care of initializing all fields of any base class that is a dataclass itself.

See the section below on init-only variables for ways to pass parameters to __post_init__() . Also see the warning about how replace() handles init=False fields.

Class variables¶

One of two places where dataclass() actually inspects the type of a field is to determine if a field is a class variable as defined in PEP 526. It does this by checking if the type of the field is typing.ClassVar . If a field is a ClassVar , it is excluded from consideration as a field and is ignored by the dataclass mechanisms. Such ClassVar pseudo-fields are not returned by the module-level fields() function.

Init-only variables¶

The other place where dataclass() inspects a type annotation is to determine if a field is an init-only variable. It does this by seeing if the type of a field is of type dataclasses.InitVar . If a field is an InitVar , it is considered a pseudo-field called an init-only field. As it is not a true field, it is not returned by the module-level fields() function. Init-only fields are added as parameters to the generated __init__() method, and are passed to the optional __post_init__() method. They are not otherwise used by dataclasses.

For example, suppose a field will be initialized from a database, if a value is not provided when creating the class:

In this case, fields() will return Field objects for i and j , but not for database .

Frozen instances¶

It is not possible to create truly immutable Python objects. However, by passing frozen=True to the dataclass() decorator you can emulate immutability. In that case, dataclasses will add __setattr__() and __delattr__() methods to the class. These methods will raise a FrozenInstanceError when invoked.

There is a tiny performance penalty when using frozen=True : __init__() cannot use simple assignment to initialize fields, and must use object.__setattr__() .

Inheritance¶

When the dataclass is being created by the dataclass() decorator, it looks through all of the class’s base classes in reverse MRO (that is, starting at object ) and, for each dataclass that it finds, adds the fields from that base class to an ordered mapping of fields. After all of the base class fields are added, it adds its own fields to the ordered mapping. All of the generated methods will use this combined, calculated ordered mapping of fields. Because the fields are in insertion order, derived classes override base classes. An example:

The final list of fields is, in order, x , y , z . The final type of x is int , as specified in class C .

The generated __init__() method for C will look like:

Re-ordering of keyword-only parameters in __init__() ¶

After the parameters needed for __init__() are computed, any keyword-only parameters are moved to come after all regular (non-keyword-only) parameters. This is a requirement of how keyword-only parameters are implemented in Python: they must come after non-keyword-only parameters.

In this example, Base.y , Base.w , and D.t are keyword-only fields, and Base.x and D.z are regular fields:

The generated __init__() method for D will look like:

Note that the parameters have been re-ordered from how they appear in the list of fields: parameters derived from regular fields are followed by parameters derived from keyword-only fields.

The relative ordering of keyword-only parameters is maintained in the re-ordered __init__() parameter list.

Default factory functions¶

If a field() specifies a default_factory , it is called with zero arguments when a default value for the field is needed. For example, to create a new instance of a list, use:

If a field is excluded from __init__() (using init=False ) and the field also specifies default_factory , then the default factory function will always be called from the generated __init__() function. This happens because there is no other way to give the field an initial value.

Mutable default values¶

Python stores default member variable values in class attributes. Consider this example, not using dataclasses:

Note that the two instances of class C share the same class variable x , as expected.

Using dataclasses, if this code was valid:

it would generate code similar to:

This has the same issue as the original example using class C . That is, two instances of class D that do not specify a value for x when creating a class instance will share the same copy of x . Because dataclasses just use normal Python class creation they also share this behavior. There is no general way for Data Classes to detect this condition. Instead, the dataclass() decorator will raise a TypeError if it detects a default parameter of type list , dict , or set . This is a partial solution, but it does protect against many common errors.

Using default factory functions is a way to create new instances of mutable types as default values for fields:

dataclasses-Классы данных

Этот модуль предоставляет декоратор и функции для автоматического добавления сгенерированных специальных методов , таких как __init__() и __repr__() , в пользовательские классы. Первоначально он был описан в PEP 557 .

Переменные-члены для использования в этих сгенерированных методах определяются с помощью аннотаций типа PEP 526 . Например, этот код:

добавит, среди прочего, __init__() который выглядит так:

Обратите внимание, что этот метод автоматически добавляется в класс: он не указан напрямую в показанном выше определении InventoryItem .

Новинка в версии 3.7.

Module contents

Эта функция является декоратором , который используется для добавления сгенерированных специальных методов к классам, как описано ниже.

Декоратор dataclass dataclass() проверяет класс, чтобы найти field s. Поле field как переменная класса, имеющая аннотацию типа . За двумя исключениями, описанными ниже, в dataclass() ничто не проверяет тип, указанный в аннотации переменной.

Порядок расположения полей во всех генерируемых методах является порядком их появления в определении класса.

Декоратор dataclass dataclass() добавит в класс различные «dunder»-методы, описанные ниже. Если какой-либо из добавленных методов уже существует в классе, поведение зависит от параметра, как описано ниже. Декоратор возвращает тот же класс, для которого он был вызван; новый класс не создается.

Если dataclass() используется как простой декоратор без параметров, он действует так, как если бы он имел значения по умолчанию, задокументированные в этой подписи. То есть эти три использования dataclass() эквивалентны:

init : если true (по умолчанию), будет сгенерирован метод __init__() .

Если класс уже определяет __init__() , этот параметр игнорируется.

repr : если true (по умолчанию), будет сгенерирован метод __repr__() . Сгенерированная строка повторения будет иметь имя класса, а также имя и повторение каждого поля в том порядке, в котором они определены в классе. Поля, помеченные как исключенные из репортажа, не включаются. Например: InventoryItem(name=’widget’, unit_price=3.0, quantity_on_hand=10) .

Если класс уже определяет __repr__() , этот параметр игнорируется.

eq : Если true (по умолчанию), будет сгенерирован метод __eq__() . Этот метод сравнивает класс по порядку, как если бы он был кортежем его полей. Оба экземпляра в сравнении должны быть одного типа.

Если класс уже определяет __eq__() , этот параметр игнорируется.

order : если true (по умолчанию False ), будут __lt__() , __le__() , __gt__() и __ge__() . Они по порядку сравнивают класс, как если бы он был кортежем его полей. Оба экземпляра в сравнении должны быть одного типа. Если order равен true, а eq — false, возникает ValueError .

Если класс уже определяет любой из __lt__() , __le__() , __gt__() , или __ge__() , а затем TypeError поднимается.

unsafe_hash : если False (по умолчанию), __hash__() создается в соответствии с тем, как установлены eq и frozen .

__hash__() используется встроенной функцией hash() , а также при добавлении объектов в хешированные коллекции, такие как словари и наборы. Наличие __hash__() означает, что экземпляры класса неизменяемы. Изменчивость — это сложное свойство, которое зависит от намерения программиста, существования и поведения __eq__() , а также значений флагов eq и frozen dataclass() .

По умолчанию dataclass() не будет неявно добавлять __hash__() если это не безопасно. Он также не будет добавлять или изменять существующий явно определенный __hash__() . Установка атрибута класса __hash__ = None имеет особое значение для Python, как описано в документации __hash__() .

Если __hash__() не определен явно или если для него установлено значение None , то dataclass() может добавить неявный __hash__() . Хотя это не рекомендуется, вы можете заставить dataclass() создать __hash__() с unsafe_hash=True . Это может быть так, если ваш класс логически неизменен, но, тем не менее, может быть изменен. Это особый вариант использования, который следует тщательно продумать.

Вот правила, регулирующие неявное создание метода __hash__() . Обратите внимание, что вы не можете одновременно иметь явный __hash__() в своем классе данных и установить unsafe_hash=True ; это приведет к TypeError .

Если eq и frozen истинны, по умолчанию dataclass() сгенерирует для вас метод __hash__() . Если eq истинно, а frozen — ложно, __hash__() будет установлено в None , помечая его как нехешируемый (что так и есть, поскольку он изменяемый). Если eq имеет значение false, __hash__() останется нетронутым, что означает, что будет использоваться метод __hash__() суперкласса (если суперкласс является object , это означает, что он вернется к хешированию на основе идентификатора).

Новинка в версии 3.10.

  • kw_only : если true (значение по умолчанию False ), то все поля будут помечены как содержащие только ключевые слова. Если поле помечено как только ключевое слово, то единственный эффект заключается в том, что параметр __init__() , сгенерированный из поля только ключевого слова, должен быть указан с ключевым словом при __init__() . Ни на какой другой аспект классов данных это никак не влияет. Подробнее см. в записи глоссария параметров . Также см . раздел KW_ONLY .

Новинка в версии 3.10.

  • slots : если true (по умолчанию False ), будет сгенерирован атрибут __slots__ и будет возвращен новый класс вместо исходного. Если __slots__ уже определен в классе, то TypeError поднимается.

Новинка в версии 3.10.

Изменено в версии 3.11: если имя поля уже включено в __slots__ базового класса, оно не будет включено в сгенерированные __slots__ , чтобы предотвратить их переопределение . Поэтому не используйте __slots__ для получения имен полей класса данных. Вместо этого используйте fields() .Чтобы иметь возможность определять унаследованные слоты, базовый класс __slots__ может быть любым итерируемым, но не итератором.

  • weakref_slot : если true (по умолчанию False ), добавьте слот с именем «__weakref__», который необходим для того, чтобы сделать экземпляр уязвимым. Ошибка указывать weakref_slot=True без указания slots=True .

Новинка в версии 3.11.

field s может дополнительно указывать значение по умолчанию, используя обычный синтаксис Python:

В этом примере и a , и b будут включены в добавленный метод __init__() , который будет определен как:

TypeError будет вызвана , если поле без значения по умолчанию следует за полем со значением по умолчанию. Это верно независимо от того, происходит ли это в отдельном классе или в результате наследования классов.

dataclasses.field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=MISSING)

Для обычных и простых случаев использования никаких других функций не требуется. Однако есть некоторые функции класса данных, требующие дополнительной информации для каждого поля. Чтобы удовлетворить эту потребность в дополнительной информации, вы можете заменить значение поля по умолчанию вызовом предоставленной функции field() . Например:

Как показано выше, значение MISSING — это контрольный объект, используемый для определения того, предоставлены ли некоторые параметры пользователем. Этот индикатор используется, потому что None является допустимым значением для некоторых параметров с определенным значением. Никакой код не должен напрямую использовать значение MISSING .

  • default : если указано, это будет значение по умолчанию для этого поля. Это необходимо, потому что сам вызов field() заменяет обычное положение значения по умолчанию.
  • default_factory : если предоставлено, это должен быть вызываемый объект с нулевым аргументом, который будет вызываться, когда для этого поля потребуется значение по умолчанию. Помимо прочего, это можно использовать для указания полей с изменяемыми значениями по умолчанию, как описано ниже. default_factory указывать и default , и default_factory .
  • init : если true (по умолчанию), это поле включается в качестве параметра в сгенерированный метод __init__() .
  • repr : если true (по умолчанию), это поле включается в строку, возвращаемую сгенерированным __repr__() .

hash : Это может быть bool или None . Если true, это поле включается в сгенерированный __hash__() . Если None (значение по умолчанию), используйте значение compare : обычно это ожидаемое поведение. Поле должно учитываться в хеше, если оно используется для сравнения. Не рекомендуется устанавливать для этого значения значение, отличное от None .

Одна из возможных причин для установки hash=False , но compare=True может заключаться в том, что вычисление хэш-значения для поля требует больших затрат, это поле необходимо для проверки на равенство и существуют другие поля, которые вносят вклад в хеш-значение типа. Даже если поле исключено из хеша, оно все равно будет использоваться для сравнения.

Новинка в версии 3.10.

Если значение поля по умолчанию задается вызовом field() , тогда атрибут класса для этого поля будет заменен указанным значением по default . Если default не указано, атрибут класса будет удален. Цель состоит в том, что после dataclass() декоратора dataclass () все атрибуты класса будут содержать значения по умолчанию для полей, как если бы само значение по умолчанию было указано. Например, после:

Атрибут класса C.z будет равен 10 , атрибут класса C.t будет равен 20 , а атрибуты класса C.x и C.y не будут установлены.

Field Объекты поля описывают каждое определенное поле. Эти объекты создаются внутри и возвращаются методомуровня модуля fields() (см. Ниже). Пользователи никогда не должны создавать экземпляробъекта Field напрямую. Его задокументированные атрибуты:

  • name : имя поля.
  • type : тип поля.
  • default , default_factory , init , repr , hash , compare , metadata и kw_only имеют то же значение и значения, что и в функции field() .

Могут существовать и другие атрибуты,но они являются частными и не должны проверяться или на них нельзя полагаться.

Возвращает кортеж объектов Field , которые определяют поля для этого класса данных. Принимает либо класс данных, либо экземпляр класса данных. Вызывает TypeError TypeError, если не передан класс данных или его экземпляр. Не возвращает псевдополя ClassVar или InitVar .

Преобразует obj класса данных в dict (используя фабричную функцию dict_factory ). Каждый класс данных преобразуется в словарь своих полей в виде пар name: value . рекурсивно используются классы данных, словари, списки и кортежи. Другие объекты копируются с помощью copy.deepcopy() .

Пример использования asdict() для вложенных классов данных:

Для создания неглубокой копии можно использовать следующее обходное решение:

asdict() вызывает TypeError , если obj не является экземпляром класса данных.

Преобразует obj класса данных в кортеж (используя фабричную функцию tuple_factory ). Каждый класс данных преобразуется в кортеж значений его полей. рекурсивно используются классы данных, словари, списки и кортежи. Другие объекты копируются с помощью copy.deepcopy() .

Продолжая предыдущий пример:

Для создания неглубокой копии можно использовать следующее обходное решение:

astuple() вызывает TypeError , если obj не является экземпляром класса данных.

dataclasses.make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)

Создает новый класс данных с именем cls_name , полями, как определено в fields , базовыми классами, как указано в bases , и инициализируется пространством имен, как указано в namespace . fields — это итерируемый объект, каждый из элементов которого является name , (name, type) или (name, type, Field) . Если указано только name , для type используется typing.Any . Значения init , repr , eq , order , unsafe_hash , frozen , match_args , kw_only , slots и weakref_slot имеют то же значение, что и в dataclass() .

Эта функция не является строго обязательной, так как любой механизм Python для создания нового класса с __annotations__ может затем применить dataclass() для преобразования этого класса в класс данных. Эта функция предоставляется для удобства. Например:

Создает новый объект того же типа, что и obj , заменяя поля значениями из changes . Если obj не является классом данных, вызывает TypeError . Если значения в changes не указывают поля, вызывает TypeError .

Вновь возвращенный объект создается путем вызова метода __init__() класса данных. Это гарантирует, что __post_init__() , если он присутствует, также будет вызван.

Переменные только для инициализации без значений по умолчанию, если таковые существуют, должны быть указаны при вызове replace() чтобы их можно было передать в __init__() и __post_init__() .

Если changes содержат какие-либо поля, которые определены как имеющие init=False , это ошибка . В этом случае будет ValueError .

Будьте предупреждены о том, как поля init=False работают во время вызова replace() . Они не копируются из исходного объекта, а инициализируются в __post_init__() , если они вообще инициализируются. Ожидается, что поля init=False будут использоваться редко и разумно. Если они используются, может быть целесообразно иметь альтернативные конструкторы классов или, возможно, пользовательский метод replace() (или аналогичный), который обрабатывает копирование экземпляров.

Верните True , если его параметр является классом данных или его экземпляром, в противном случае верните False .

Если вам нужно знать, является ли класс экземпляром класса данных (а не самим классом данных), добавьте дополнительную проверку not isinstance(obj, type) :

Значение,сигнализирующее об отсутствии значения по умолчанию или default_factory.

Контрольное значение, используемое в качестве аннотации типа. Любые поля после псевдополя с типом KW_ONLY помечаются как поля только для ключевых слов. Обратите внимание, что псевдополе типа KW_ONLY в противном случае полностью игнорируется. Это включает имя такого поля. По соглашению для поля KW_ONLY используется имя _ . Поля только для ключевых слов означают параметры __init__() которые должны быть указаны как ключевые слова при создании экземпляра класса.

В этом примере поля y и z будут помечены как поля, содержащие только ключевые слова:

В одном классе данных указывать более одного поля типа KW_ONLY является ошибкой .

Новинка в версии 3.10.

__setattr__() когда неявно определенный __setattr __ () или __delattr__() вызывается в классе данных, который был определен с помощью frozen=True . Это подкласс AttributeError .

Похожие статьи