Can you explain this code for me(type hints)?

What does this code mean?

class Foo:

and is it equivalent to this code?

class Foo:
    x.self = x
    y.self = y

No, they’re not assignments at all. They’re more like documentation, telling you that instances of Foo should have two attributes - x and y. x will be an integer, while y will be a string. Instead of using a docstring or comments like what was done before type hints, it’s a standardised syntax that many tools are able to understand.

1 Like

Thank you some much.

You may have seen the first fragment in the context of dataclasses? If so, it would be

from dataclasses import dataclass
class Foo:
    x: int
    y: int

In this case the dataclass decorator defines the class such that x and y become two member fields.
So, you get:

>>> foo = Foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Foo.__init__() missing 2 required positional arguments: 'x' and 'y'
>>> foo = Foo(x=1, y=2)
>>> foo
Foo(x=1, y=2)
>>> foo.x
>>> foo.y

Since the fields don’t have a default they need to specified when using Foo.

If you leave out the @dataclass decorator, the code snippet is valid Python code, but I wouldn’t really know what its use would be. In that case x and y are just added to the Foo.__annotations__ dictionary, but it’s unclear what you’d be using them for.

The second code snippet is invalid Python code, since x and y (used as right-hand terms) are undefined. Also, you’ll never see Python expressions of the form “x.self”, even though they could be made perfectly valid, since “self” is usually only used inside class member functions to refer to this class instance (like “this” in C++), and it’s used only as self.some_field, self.some_function(...). Using “self” as name of a field inside a class instance, so allowing “x.self”, would be extremely confusing.

And (as third point), you’ll (almost) never see something like x.some_field = x since you’d be creating a circular, self-referential data instance. Python does allow this… but you probably want to stay away from that :slight_smile:

You didn’t mention pydantic here, so I didn’t think of that at first. But if Foo has a pydantic BaseModel as base class, then pydantic will also do something similar as dataclasses and turn those annotations into actual class members (see: Welcome to Pydantic - Pydantic for an example).