Python Slots Default Value

Source code:Lib/dataclasses.py

  1. Python Default Value For Input
  2. Python Slots Default Value Sheet
  3. Python Slots Default Values
  4. Python Slots Default Value Guide
  5. Set Default Parameter Value Python
  6. Python __slots__ Default Values

This module provides a decorator and functions for automaticallyadding generated special methods such as __init__() and__repr__() to user-defined classes. It was originally describedin PEP 557.

However, this is not valid Python. If a parameter has a default value, all following parameters must also have a default value. In other words, if a field in a base class has a default value, then all new fields added in a subclass must have default values as well. Another thing to be aware of is how fields are ordered in a subclass. The mobile casino has taken Pythonslots Default Values the concept of personalized gaming to a whole new level. Now you can play on the go 24×7 regardless of Pythonslots Default Values where you are. All you need is a smartphone that gives you Internet access via 3G, 4G, LTE, or Wi-Fi.

Python Slots Default Value

The member variables to use in these generated methods are definedusing 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 notdirectly specified in the InventoryItem definition shown above.

New in version 3.7.

Module-level decorators, classes, and functions¶

@dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)

This function is a decorator that is used to add generatedspecial methods to classes, as described below.

Python Default Value For Input

The dataclass() decorator examines the class to findfields. A field is defined as class variable that has atype annotation. With twoexceptions 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 theorder in which they appear in the class definition.

The dataclass() decorator will add various “dunder” methods tothe class, described below. If any of the added methods alreadyexist on the class, the behavior depends on the parameter, as documentedbelow. The decorator returns the same class that is called on; no newclass 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 thissignature. That is, these three uses of dataclass() areequivalent:

The parameters to dataclass() are:

  • init: If true (the default), a __init__() method will begenerated.

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

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

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

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

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

  • order: If true (the default is False), __lt__(),__le__(), __gt__(), and __ge__() methods will begenerated. These compare the class as if it were a tuple of itsfields, in order. Both instances in the comparison must be of theidentical type. If order is true and eq is false, aValueError is raised.

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

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

    __hash__() is used by built-in hash(), and when objects areadded 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’sintent, the existence and behavior of __eq__(), and the values ofthe 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 anexisting explicitly defined __hash__() method. Setting the classattribute __hash__=None has a specific meaning to Python, asdescribed in the __hash__() documentation.

    If __hash__() is not explicit 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 caseif 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 resultin a TypeError.

    If eq and frozen are both true, by default dataclass() willgenerate a __hash__() method for you. If eq is true andfrozen is false, __hash__() will be set to None, marking itunhashable (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 isobject, this means it will fall back to id-based hashing).

  • frozen: If true (the default is False), assigning to fields willgenerate an exception. This emulates read-only frozen instances. If__setattr__() or __delattr__() is defined in the class, thenTypeError is raised. See the discussion below.

fields may optionally specify a default value, using normalPython 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 valuefollows a field with a default value. This is true either when thisoccurs in a single class, or as a result of class inheritance.

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

For common and simple use cases, no other functionality isrequired. There are, however, some dataclass features thatrequire additional per-field information. To satisfy this need foradditional information, you can replace the default field valuewith a call to the provided field() function. For example:

As shown above, the MISSING value is a sentinel object used todetect if the default and default_factory parameters areprovided. This sentinel is used because None is a valid valuefor default. No code should directly use the MISSINGvalue.

The parameters to field() are:

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

  • default_factory: If provided, it must be a zero-argumentcallable that will be called when a default value is needed forthis field. Among other purposes, this can be used to specifyfields with mutable default values, as discussed below. It is anerror to specify both default and default_factory.

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

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

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

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

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

  • metadata: This can be a mapping or None. None is treated asan empty dict. This value is wrapped inMappingProxyType() to make it read-only, and exposedon the Field object. It is not used at all by DataClasses, and is provided as a third-party extension mechanism.Multiple third-parties can each have their own key, to use as anamespace in the metadata.

If the default value of a field is specified by a call tofield(), then the class attribute for this field will bereplaced by the specified default value. If no default isprovided, then the class attribute will be deleted. The intent isthat after the dataclass() decorator runs, the classattributes will all contain the default values for the fields, justas if the default value itself were specified. For example,after:

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

class dataclasses.Field

Field objects describe each defined field. These objectsare created internally, and are returned by the fields()module-level method (see below). Users should never instantiate aField 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, and metadata have the identical meaning andvalues as they do in the field() declaration.

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

dataclasses.fields(class_or_instance)

Returns a tuple of Field objects that define the fields for thisdataclass. 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(instance, *, dict_factory=dict)

Converts the dataclass instance to a dict (by using thefactory function dict_factory). Each dataclass is convertedto a dict of its fields, as name:value pairs. dataclasses, dicts,lists, and tuples are recursed into. For example:

Raises TypeError if instance is not a dataclass instance.

dataclasses.astuple(instance, *, tuple_factory=tuple)
Slots

Converts the dataclass instance to a tuple (by using thefactory function tuple_factory). Each dataclass is convertedto a tuple of its field values. dataclasses, dicts, lists, andtuples are recursed into.

Continuing from the previous example:

Raises TypeError if instance 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)

Creates a new dataclass with name cls_name, fields as definedin fields, base classes as given in bases, and initializedwith a namespace as given in namespace. fields is aniterable 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, and frozen havethe same meaning as they do in dataclass().

This function is not strictly required, because any Pythonmechanism for creating a new class with __annotations__ canthen apply the dataclass() function to convert that class toa dataclass. This function is provided as a convenience. Forexample:

Is equivalent to:

dataclasses.replace(instance, /, **changes)

Creates a new object of the same type of instance, replacingfields with values from changes. If instance is not a DataClass, raises TypeError. If values in changes do notspecify 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 bespecified 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 aredefined as having init=False. A ValueError will be raisedin this case.

Be forewarned about how init=False fields work during a call toreplace(). They are not copied from the source object, butrather are initialized in __post_init__(), if they’reinitialized at all. It is expected that init=False fields willbe rarely and judiciously used. If they are used, it might be wiseto have alternate class constructors, or perhaps a customreplace() (or similarly named) method which handles instancecopying.

dataclasses.is_dataclass(class_or_instance)

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 (andnot a dataclass itself), then add a further check for notisinstance(obj,type):

Post-init processing¶

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

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

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

Class variables¶

One of two places where dataclass() actually inspects the typeof a field is to determine if a field is a class variable as definedin PEP 526. It does this by checking if the type of the field istyping.ClassVar. If a field is a ClassVar, it is excludedfrom consideration as a field and is ignored by the dataclassmechanisms. Such ClassVar pseudo-fields are not returned by themodule-level fields() function.

Init-only variables¶

The other place where dataclass() inspects a type annotation is todetermine if a field is an init-only variable. It does this by seeingif the type of a field is of type dataclasses.InitVar. If a fieldis an InitVar, it is considered a pseudo-field called an init-onlyfield. As it is not a true field, it is not returned by themodule-level fields() function. Init-only fields are added asparameters to the generated __init__() method, and are passed tothe optional __post_init__() method. They are not otherwise usedby dataclasses.

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

In this case, fields() will return Field objects for i andj, 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 canemulate immutability. In that case, dataclasses will add__setattr__() and __delattr__() methods to the class. Thesemethods will raise a FrozenInstanceError when invoked.

There is a tiny performance penalty when using frozen=True:__init__() cannot use simple assignment to initialize fields, andmust 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 (thatis, 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 fieldsto the ordered mapping. All of the generated methods will use thiscombined, calculated ordered mapping of fields. Because the fieldsare in insertion order, derived classes override base classes. Anexample:

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

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

Default factory functions¶

If a field() specifies a default_factory, it is called withzero arguments when a default value for the field is needed. Forexample, 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 defaultfactory function will always be called from the generated__init__() function. This happens because there is no otherway 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 classvariable 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 forx when creating a class instance will share the same copy ofx. Because dataclasses just use normal Python class creationthey also share this behavior. There is no general way for DataClasses to detect this condition. Instead, dataclasses will raise aTypeError if it detects a default parameter of type list,dict, or set. This is a partial solution, but it does protectagainst many common errors.

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

Python Slots Default Value Sheet

Exceptions¶

Python Slots Default Values

exception dataclasses.FrozenInstanceError

Raised when an implicitly defined __setattr__() or__delattr__() is called on a dataclass which was defined withfrozen=True.

Previous Chapter: OOP, Inheritance Example
Next Chapter: Classes and Class Creation

Slots

Avoiding Dynamically Created Attributes

The attributes of objects are stored in a dictionary __dict__. Like any other dictionary, a dictionary used for attribute storage doesn't have a fixed number of elements. In other words, you can add elements to dictionaries after they are defined, as we have seen in our chapter on dictionaries. This is the reason, why you can dynamically add attributes to objects of classes that we have created so far:

The dictionary containing the attributes of 'a' can be accessed like this:

You might have wondered that you can dynamically add attributes to the classes, we have defined so far, but that you can't do this with built-in classes like 'int', or 'list':

Python Slots Default Value Guide

Using a dictionary for attribute storage is very convenient, but it can mean a waste of space for objects, which have only a small amount of instance variables. The space consumption can become critical when creating large numbers of instances. Slots are a nice way to work around this space consumption problem. Instead of having a dynamic dict that allows adding attributes to objects dynamically, slots provide a static structure which prohibits additions after the creation of an instance.

When we design a class, we can use slots to prevent the dynamic creation of attributes. To define slots, you have to define a list with the name __slots__. The list has to contain all the attributes, you want to use. We demonstrate this in the following class, in which the slots list contains only the name for an attribute 'val'.

If we start this program, we can see, that it is not possible to create dynamically a new attribute. We fail to create an attribute 'new'.

Set Default Parameter Value Python

We mentioned in the beginning that slots are preventing a waste of space with objects. Since Python 3.3 this advantage is not as impressive any more. With Python 3.3 Key-Sharing Dictionaries are used for the storage of objects. The attributes of the instances are capable of sharing part of their internal storage between each other, i.e. the part which stores the keys and their corresponding hashes. This helps reducing the memory consumption of programs, which create many instances of non-builtin types.

Previous Chapter: OOP, Inheritance Example
Next Chapter: Classes and Class Creation

Python __slots__ Default Values


Comments are closed.