Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Document ClassVar #5733

Merged
merged 3 commits into from
Oct 16, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 45 additions & 1 deletion docs/source/class_basics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ a type annotation:
a = A()
a.x = [1] # OK

As in Python generally, a variable defined in the class body can used
As in Python generally, a variable defined in the class body can be used
as a class or an instance variable.

Type comments work as well, if you need to support Python versions earlier
Expand Down Expand Up @@ -77,6 +77,50 @@ to it explicitly using ``self``:
a = self
a.x = 1 # Error: 'x' not defined

Class attribute annotations
***************************

Mypy supports annotations for class and instance
nanjekyejoannah marked this conversation as resolved.
Show resolved Hide resolved
variables in class bodies and methods. Use ``ClassVar`` to
indicate to the static type checker that this variable
nanjekyejoannah marked this conversation as resolved.
Show resolved Hide resolved
should not be set on instances.
nanjekyejoannah marked this conversation as resolved.
Show resolved Hide resolved

A class attribute without the ``ClassVar`` annotation can be used as
a class variable. Mypy won't prevent it from being used as an
instance variable.

.. code-block:: python

class A:
y: ClassVar[Dict[str, int]] = {} # class variable
z: int = 10 # instance variable

The following are worth noting about ``ClassVar``:

- It accepts only types and cannot be further subscribed.

- It is not a class itself, and should not be used with
isinstance() or issubclass().

- It does not change Python runtime behavior, but it can
be used by third-party type checkers. For example, a type checker
might flag the following code as an error:

.. code-block:: python

a = A(3000)
a.y = {} # Error, setting class variable on instance
a.z = {} # This is OK


Also `` y: ClassVar = 0 `` is valid (without square brackets). The type of
the variable will be implicitly ``Any``. This behavior will change in the future.

.. note::
A ``ClassVar`` parameter cannot include any type variables,
regardless of the level of nesting: ``ClassVar[T]`` and ``ClassVar[List[Set[T]]]``
are both invalid if ``T`` is a type variable.

Overriding statically typed methods
***********************************

Expand Down