<commit_before>Initialization
==============

In Python, instance initialization happens in the ``__init__`` method.
Generally speaking, you should keep as little logic as possible in it, and you should think about what the class needs and not how it is going to be instantiated.

Passing complex objects into ``__init__`` and then using them to derive data for the class unnecessarily couples your new class with the old class which makes it harder to test and also will cause problems later.

So assuming you use an ORM and want to extract 2D points from a row object, do not write code like this::

    class Point:
        def __init__(self, database_row):
            self.x = database_row.x
            self.y = database_row.y

    pt = Point(row)

Instead, write a `classmethod` that will extract it for you::

   @define
   class Point:
       x: float
       y: float

       @classmethod
       def from_row(cls, row):
           return cls(row.x, row.y)

   pt = Point.from_row(row)

Now you can instantiate ``Point``\ s without creating fake row objects in your tests and you can have as many smart creation helpers as you want, in case more data sources appear.

For similar reasons, we strongly discourage from patterns like::

   pt = Point(**row.attributes)

which couples your classes to the database data model.
Try to design your classes in a way that is clean and convenient to use -- not based on your database format.
The database format can change anytime and you're stuck with a bad class design that is hard to change.
Embrace functions and classmethods as a filter between reality and what's best for you to work with.

If you look for object serialization, there's a bunch of projects listed on our ``attrs`` extensions `Wiki page`_.
Some of them even support nested schemas.


Private Attributes
------------------

One thing people tend to find confusing is the treatment of private attributes that start with an underscore.
``attrs`` follows the doctrine that `there is no such thing as a private argument`_ and strips the underscores from the name when writing the ``__init__`` method signature:

.. doctest::

   >>> import inspect, attr, attrs
   >>> from attr import define
   >>> @define
   ... class C:
   ...    _x: int
   >>> inspect.signature(C.__init__)
   <Signature (self, x: int) -> None>

There really isn't a right or wrong, it's a matter of taste.
But it's important to be aware of it because it can lead to surprising syntax errors:

.. doctest::

   >>> @define
   ... class C:
   ...    _1: int
   Traceback (most recent call last):
      ...
   SyntaxError: invalid syntax

In this case a valid attribute name ``_1`` got transformed into an invalid argument name ``1``.


Defaults
--------

Sometimes you don't want to pass all attribute values to a class.
And sometimes, certain attributes aren't even intended to be passed but you want to allow for customization anyways for easier testing.

This is when default values come into play:

.. doctest::

   >>> from attr import define, field, Factory

   >>> @define
   ... class C:
   ...     a: int = 42
   ...     b: list = field(factory=list)
   ...     c: list = Factory(list)  # syntactic sugar for above
   ...     d: dict = field()
   ...     @d.default
   ...     def _any_name_except_a_name_of_an_attribute(self):
   ...        return {}
   >>> C()
   C(a=42, b=[], c=[], d={})

It's important that the decorated method -- or any other method or property! -- doesn't have the same name as the attribute, otherwise it would overwrite the attribute definition.

Please note that as with function and method signatures, ``default=[]`` will *not* do what you may think it might do:

.. doctest::

   >>> @define
   ... class C:
   ...     x = []
   >>> i = C()
   >>> k = C()
   >>> i.x.append(42)
   >>> k.x
   [42]


This is why ``attrs`` comes with factory options.

.. warning::

   Please note that the decorator based defaults have one gotcha:
   they are executed when the attribute is set, that means depending on the order of attributes, the ``self`` object may not be fully initialized when they're called.

   Therefore you should use ``self`` as little as possible.

   Even the smartest of us can `get confused`_ by what happens if you pass partially initialized objects around.


.. _validators:

Validators
----------

Another thing that definitely *does* belong in ``__init__`` is checking the resulting instance for invariants.
This is why ``attrs`` has the concept of validators.


Decorator
~~~~~~~~~

The most straightforward way is using the attribute's ``validator`` method as a decorator.

The method has to accept three arguments:

#. the *instance* that's being validated (aka ``self``),
#. the *attribute* that it's validating, and finally
#. the *value* that is passed for it.

If the value does not pass the validator's standards, it just raises an appropriate exception.

   >>> @define
   ... class C:
   ...     x: int = field()
   ...     @x.validator
   ...     def _check_x(self, attribute, value):
   ...         if value > 42:
   ...             raise ValueError("x must be smaller or equal to 42")
   >>> C(42)
   C(x=42)
   >>> C(43)
   Traceback (most recent call last):
      ...
   ValueError: x must be smaller or equal to 42

Again, it's important that the decorated method doesn't have the same name as the attribute and that the `attrs.field()` helper is used.


Callables
~~~~~~~~~

If you want to re-use your validators, you should have a look at the ``validator`` argument to `attrs.field`.

It takes either a callable or a list of callables (usually functions) and treats them as validators that receive the same arguments as with the decorator approach.

Since the validators run *after* the instance is initialized, you can refer to other attributes while validating:

.. doctest::

   >>> def x_smaller_than_y(instance, attribute, value):
   ...     if value >= instance.y:
   ...         raise ValueError("'x' has to be smaller than 'y'!")
   >>> @define
   ... class C:
   ...     x = field(validator=[attrs.validators.instance_of(int),
   ...                          x_smaller_than_y])
   ...     y = field()
   >>> C(x=3, y=4)
   C(x=3, y=4)
   >>> C(x=4, y=3)
   Traceback (most recent call last):
      ...
   ValueError: 'x' has to be smaller than 'y'!

This example also shows of some syntactic sugar for using the `attrs.validators.and_` validator: if you pass a list, all validators have to pass.<commit_msg>Clarify validator arguments are passed as pos args<commit_after>Initialization
==============

In Python, instance initialization happens in the ``__init__`` method.
Generally speaking, you should keep as little logic as possible in it, and you should think about what the class needs and not how it is going to be instantiated.

Passing complex objects into ``__init__`` and then using them to derive data for the class unnecessarily couples your new class with the old class which makes it harder to test and also will cause problems later.

So assuming you use an ORM and want to extract 2D points from a row object, do not write code like this::

    class Point:
        def __init__(self, database_row):
            self.x = database_row.x
            self.y = database_row.y

    pt = Point(row)

Instead, write a `classmethod` that will extract it for you::

   @define
   class Point:
       x: float
       y: float

       @classmethod
       def from_row(cls, row):
           return cls(row.x, row.y)

   pt = Point.from_row(row)

Now you can instantiate ``Point``\ s without creating fake row objects in your tests and you can have as many smart creation helpers as you want, in case more data sources appear.

For similar reasons, we strongly discourage from patterns like::

   pt = Point(**row.attributes)

which couples your classes to the database data model.
Try to design your classes in a way that is clean and convenient to use -- not based on your database format.
The database format can change anytime and you're stuck with a bad class design that is hard to change.
Embrace functions and classmethods as a filter between reality and what's best for you to work with.

If you look for object serialization, there's a bunch of projects listed on our ``attrs`` extensions `Wiki page`_.
Some of them even support nested schemas.


Private Attributes
------------------

One thing people tend to find confusing is the treatment of private attributes that start with an underscore.
``attrs`` follows the doctrine that `there is no such thing as a private argument`_ and strips the underscores from the name when writing the ``__init__`` method signature:

.. doctest::

   >>> import inspect, attr, attrs
   >>> from attr import define
   >>> @define
   ... class C:
   ...    _x: int
   >>> inspect.signature(C.__init__)
   <Signature (self, x: int) -> None>

There really isn't a right or wrong, it's a matter of taste.
But it's important to be aware of it because it can lead to surprising syntax errors:

.. doctest::

   >>> @define
   ... class C:
   ...    _1: int
   Traceback (most recent call last):
      ...
   SyntaxError: invalid syntax

In this case a valid attribute name ``_1`` got transformed into an invalid argument name ``1``.


Defaults
--------

Sometimes you don't want to pass all attribute values to a class.
And sometimes, certain attributes aren't even intended to be passed but you want to allow for customization anyways for easier testing.

This is when default values come into play:

.. doctest::

   >>> from attr import define, field, Factory

   >>> @define
   ... class C:
   ...     a: int = 42
   ...     b: list = field(factory=list)
   ...     c: list = Factory(list)  # syntactic sugar for above
   ...     d: dict = field()
   ...     @d.default
   ...     def _any_name_except_a_name_of_an_attribute(self):
   ...        return {}
   >>> C()
   C(a=42, b=[], c=[], d={})

It's important that the decorated method -- or any other method or property! -- doesn't have the same name as the attribute, otherwise it would overwrite the attribute definition.

Please note that as with function and method signatures, ``default=[]`` will *not* do what you may think it might do:

.. doctest::

   >>> @define
   ... class C:
   ...     x = []
   >>> i = C()
   >>> k = C()
   >>> i.x.append(42)
   >>> k.x
   [42]


This is why ``attrs`` comes with factory options.

.. warning::

   Please note that the decorator based defaults have one gotcha:
   they are executed when the attribute is set, that means depending on the order of attributes, the ``self`` object may not be fully initialized when they're called.

   Therefore you should use ``self`` as little as possible.

   Even the smartest of us can `get confused`_ by what happens if you pass partially initialized objects around.


.. _validators:

Validators
----------

Another thing that definitely *does* belong in ``__init__`` is checking the resulting instance for invariants.
This is why ``attrs`` has the concept of validators.


Decorator
~~~~~~~~~

The most straightforward way is using the attribute's ``validator`` method as a decorator.

The method has to accept three arguments:

#. the *instance* that's being validated (aka ``self``),
#. the *attribute* that it's validating, and finally
#. the *value* that is passed for it.

These values are passed as *positional arguments*, therefore their names don't matter.

If the value does not pass the validator's standards, it just raises an appropriate exception.

   >>> @define
   ... class C:
   ...     x: int = field()
   ...     @x.validator
   ...     def _check_x(self, attribute, value):
   ...         if value > 42:
   ...             raise ValueError("x must be smaller or equal to 42")
   >>> C(42)
   C(x=42)
   >>> C(43)
   Traceback (most recent call last):
      ...
   ValueError: x must be smaller or equal to 42

Again, it's important that the decorated method doesn't have the same name as the attribute and that the `attrs.field()` helper is used.


Callables
~~~~~~~~~

If you want to re-use your validators, you should have a look at the ``validator`` argument to `attrs.field`.

It takes either a callable or a list of callables (usually functions) and treats them as validators that receive the same arguments as with the decorator approach.
Also as with the decorator approach, they are passed as *positional arguments* so you can name them however you want.

Since the validators run *after* the instance is initialized, you can refer to other attributes while validating:

.. doctest::

   >>> def x_smaller_than_y(instance, attribute, value):
   ...     if value >= instance.y:
   ...         raise ValueError("'x' has to be smaller than 'y'!")
   >>> @define
   ... class C:
   ...     x = field(validator=[attrs.validators.instance_of(int),
   ...                          x_smaller_than_y])
   ...     y = field()
   >>> C(x=3, y=4)
   C(x=3, y=4)
   >>> C(x=4, y=3)
   Traceback (most recent call last):
      ...
   ValueError: 'x' has to be smaller than 'y'!

This example also shows of some syntactic sugar for using the `attrs.validators.and_` validator: if you pass a list, all validators have to pass.
{'fraction_non_alphanumeric': 0.10071996968548692, 'fraction_numerical': 0.004547176960970065, 'mean_word_length': 2.9806938159879337, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 131, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '599008', 'n_tokens_mistral': 3690, 'n_tokens_neox': 3541, 'n_words': 1792}