| 1 |
.. _native-classes: |
| 2 |
|
| 3 |
Native classes |
| 4 |
============== |
| 5 |
|
| 6 |
Classes in compiled modules are *native classes* by default (some |
| 7 |
exceptions are discussed below). Native classes are compiled to C |
| 8 |
extension classes, which have some important differences from normal |
| 9 |
Python classes. Native classes are similar in many ways to built-in |
| 10 |
types, such as ``int``, ``str``, and ``list``. |
| 11 |
|
| 12 |
Immutable namespaces |
| 13 |
-------------------- |
| 14 |
|
| 15 |
The type object namespace of native classes is mostly immutable (but |
| 16 |
class variables can be assigned to):: |
| 17 |
|
| 18 |
class Cls: |
| 19 |
def method1(self) -> None: |
| 20 |
print("method1") |
| 21 |
|
| 22 |
def method2(self) -> None: |
| 23 |
print("method2") |
| 24 |
|
| 25 |
Cls.method1 = Cls.method2 # Error |
| 26 |
Cls.new_method = Cls.method2 # Error |
| 27 |
|
| 28 |
Only attributes defined within a class definition (or in a base class) |
| 29 |
can be assigned to (similar to using ``__slots__``):: |
| 30 |
|
| 31 |
class Cls: |
| 32 |
x: int |
| 33 |
|
| 34 |
def __init__(self, y: int) -> None: |
| 35 |
self.x = 0 |
| 36 |
self.y = y |
| 37 |
|
| 38 |
def method(self) -> None: |
| 39 |
self.z = "x" |
| 40 |
|
| 41 |
o = Cls(0) |
| 42 |
print(o.x, o.y) # OK |
| 43 |
o.z = "y" # OK |
| 44 |
o.extra = 3 # Error: no attribute "extra" |
| 45 |
|
| 46 |
.. _inheritance: |
| 47 |
|
| 48 |
Inheritance |
| 49 |
----------- |
| 50 |
|
| 51 |
Only single inheritance is supported from native classes (except for |
| 52 |
:ref:`traits <trait-types>`). Most non-native extension classes can't |
| 53 |
be used as base classes, but regular Python classes can be used as |
| 54 |
base classes unless they use unsupported metaclasses (see below for |
| 55 |
more about this). |
| 56 |
|
| 57 |
These non-native extension classes can be used as base classes of native |
| 58 |
classes: |
| 59 |
|
| 60 |
* ``object`` |
| 61 |
* ``dict`` (and ``dict[k, v]``) |
| 62 |
* ``BaseException`` |
| 63 |
* ``Exception`` |
| 64 |
* ``ValueError`` |
| 65 |
* ``IndexError`` |
| 66 |
* ``LookupError`` |
| 67 |
* ``UserWarning`` |
| 68 |
|
| 69 |
By default, a non-native class can't inherit a native class, and you |
| 70 |
can't inherit from a native class outside the compilation unit that |
| 71 |
defines the class. You can enable these through |
| 72 |
``mypy_extensions.mypyc_attr``:: |
| 73 |
|
| 74 |
from mypy_extensions import mypyc_attr |
| 75 |
|
| 76 |
@mypyc_attr(allow_interpreted_subclasses=True) |
| 77 |
class Cls: |
| 78 |
... |
| 79 |
|
| 80 |
Allowing interpreted subclasses has only minor impact on performance |
| 81 |
of instances of the native class. Accessing methods and attributes of |
| 82 |
a *non-native* subclass (or a subclass defined in another compilation |
| 83 |
unit) will be slower, since it needs to use the normal Python |
| 84 |
attribute access mechanism. |
| 85 |
|
| 86 |
You need to install ``mypy-extensions`` to use ``@mypyc_attr``: |
| 87 |
|
| 88 |
.. code-block:: text |
| 89 |
|
| 90 |
pip install --upgrade mypy-extensions |
| 91 |
|
| 92 |
Additionally, mypyc recognizes these base classes as special, and |
| 93 |
understands how they alter the behavior of classes (including native |
| 94 |
classes) that subclass them: |
| 95 |
|
| 96 |
* ``typing.NamedTuple`` |
| 97 |
* ``typing.Generic`` |
| 98 |
* ``typing.Protocol`` |
| 99 |
* ``enum.Enum`` |
| 100 |
|
| 101 |
Class variables |
| 102 |
--------------- |
| 103 |
|
| 104 |
Class variables must be explicitly declared using ``attr: ClassVar`` |
| 105 |
or ``attr: ClassVar[<type>]``. You can't assign to a class variable |
| 106 |
through an instance. Example:: |
| 107 |
|
| 108 |
from typing import ClassVar |
| 109 |
|
| 110 |
class Cls: |
| 111 |
cv: ClassVar = 0 |
| 112 |
|
| 113 |
Cls.cv = 2 # OK |
| 114 |
o = Cls() |
| 115 |
print(o.cv) # OK (2) |
| 116 |
o.cv = 3 # Error! |
| 117 |
|
| 118 |
.. tip:: |
| 119 |
|
| 120 |
Constant class variables can be declared using ``typing.Final`` or |
| 121 |
``typing.Final[<type>]``. |
| 122 |
|
| 123 |
Generic native classes |
| 124 |
---------------------- |
| 125 |
|
| 126 |
Native classes can be generic. Type variables are *erased* at runtime, |
| 127 |
and instances don't keep track of type variable values. |
| 128 |
|
| 129 |
Compiled code thus can't check the values of type variables when |
| 130 |
performing runtime type checks. These checks are delayed to when |
| 131 |
reading a value with a type variable type:: |
| 132 |
|
| 133 |
from typing import TypeVar, Generic, cast |
| 134 |
|
| 135 |
T = TypeVar('T') |
| 136 |
|
| 137 |
class Box(Generic[T]): |
| 138 |
def __init__(self, item: T) -> None: |
| 139 |
self.item = item |
| 140 |
|
| 141 |
x = Box(1) # Box[int] |
| 142 |
y = cast(Box[str], x) # OK (type variable value not checked) |
| 143 |
y.item # Runtime error: item is "int", but "str" expected |
| 144 |
|
| 145 |
Metaclasses |
| 146 |
----------- |
| 147 |
|
| 148 |
Most metaclasses aren't supported with native classes, since their |
| 149 |
behavior is too dynamic. You can use these metaclasses, however: |
| 150 |
|
| 151 |
* ``abc.ABCMeta`` |
| 152 |
* ``typing.GenericMeta`` (used by ``typing.Generic``) |
| 153 |
|
| 154 |
.. note:: |
| 155 |
|
| 156 |
If a class definition uses an unsupported metaclass, *mypyc |
| 157 |
compiles the class into a regular Python class* (non-native |
| 158 |
class). |
| 159 |
|
| 160 |
Class decorators |
| 161 |
---------------- |
| 162 |
|
| 163 |
Similar to metaclasses, most class decorators aren't supported with |
| 164 |
native classes, as they are usually too dynamic. These class |
| 165 |
decorators can be used with native classes, however: |
| 166 |
|
| 167 |
* ``mypy_extensions.trait`` (for defining :ref:`trait types <trait-types>`) |
| 168 |
* ``mypy_extensions.mypyc_attr`` (see :ref:`above <inheritance>`) |
| 169 |
* ``dataclasses.dataclass`` |
| 170 |
* ``@attr.s(auto_attribs=True)`` |
| 171 |
|
| 172 |
Dataclasses and attrs classes have partial native support, and they aren't as |
| 173 |
efficient as pure native classes. |
| 174 |
|
| 175 |
.. note:: |
| 176 |
|
| 177 |
If a class definition uses an unsupported class decorator, *mypyc |
| 178 |
compiles the class into a regular Python class* (non-native class). |
| 179 |
|
| 180 |
Defining non-native classes |
| 181 |
--------------------------- |
| 182 |
|
| 183 |
You can use the ``@mypy_extensions.mypyc_attr(...)`` class decorator |
| 184 |
with an argument ``native_class=False`` to explicitly define normal |
| 185 |
Python classes (non-native classes):: |
| 186 |
|
| 187 |
from mypy_extensions import mypyc_attr |
| 188 |
|
| 189 |
@mypyc_attr(native_class=False) |
| 190 |
class NonNative: |
| 191 |
def __init__(self) -> None: |
| 192 |
self.attr = 1 |
| 193 |
|
| 194 |
setattr(NonNative, "extra", 1) # Ok |
| 195 |
|
| 196 |
This only has an effect in classes compiled using mypyc. Non-native |
| 197 |
classes are significantly less efficient than native classes, but they |
| 198 |
are sometimes necessary to work around the limitations of native classes. |
| 199 |
|
| 200 |
Non-native classes can use arbitrary metaclasses and class decorators, |
| 201 |
and they support flexible multiple inheritance. Mypyc will still |
| 202 |
generate a compile-time error if you try to assign to a method, or an |
| 203 |
attribute that is not defined in a class body, since these are static |
| 204 |
type errors detected by mypy:: |
| 205 |
|
| 206 |
o = NonNative() |
| 207 |
o.extra = "x" # Static type error: "extra" not defined |
| 208 |
|
| 209 |
However, these operations still work at runtime, including in modules |
| 210 |
that are not compiled using mypyc. You can also use ``setattr`` and |
| 211 |
``getattr`` for dynamic access of arbitrary attributes. Expressions |
| 212 |
with an ``Any`` type are also not type checked statically, allowing |
| 213 |
access to arbitrary attributes:: |
| 214 |
|
| 215 |
a: Any = o |
| 216 |
a.extra = "x" # Ok |
| 217 |
|
| 218 |
setattr(o, "extra", "y") # Also ok |
| 219 |
|
| 220 |
Implicit non-native classes |
| 221 |
--------------------------- |
| 222 |
|
| 223 |
If a compiled class uses an unsupported metaclass or an unsupported |
| 224 |
class decorator, it will implicitly be a non-native class, as |
| 225 |
discussed above. You can still use ``@mypyc_attr(native_class=False)`` |
| 226 |
to explicitly mark it as a non-native class. |
| 227 |
|
| 228 |
Explicit native classes |
| 229 |
----------------------- |
| 230 |
|
| 231 |
You can use ``@mypyc_attr(native_class=True)`` to explicitly declare a |
| 232 |
class as a native class. It will be a compile-time error if mypyc |
| 233 |
can't compile the class as a native class. You can use this to avoid |
| 234 |
accidentally defining implicit non-native classes. |
| 235 |
|
| 236 |
Deleting attributes |
| 237 |
------------------- |
| 238 |
|
| 239 |
By default, attributes defined in native classes can't be deleted. You |
| 240 |
can explicitly allow certain attributes to be deleted by using |
| 241 |
``__deletable__``:: |
| 242 |
|
| 243 |
class Cls: |
| 244 |
x: int = 0 |
| 245 |
y: int = 0 |
| 246 |
other: int = 0 |
| 247 |
|
| 248 |
__deletable__ = ['x', 'y'] # 'x' and 'y' can be deleted |
| 249 |
|
| 250 |
o = Cls() |
| 251 |
del o.x # OK |
| 252 |
del o.y # OK |
| 253 |
del o.other # Error |
| 254 |
|
| 255 |
You must initialize the ``__deletable__`` attribute in the class body, |
| 256 |
using a list or a tuple expression with only string literal items that |
| 257 |
refer to attributes. These are not valid:: |
| 258 |
|
| 259 |
a = ['x', 'y'] |
| 260 |
|
| 261 |
class Cls: |
| 262 |
x: int |
| 263 |
y: int |
| 264 |
|
| 265 |
__deletable__ = a # Error: cannot use variable 'a' |
| 266 |
|
| 267 |
__deletable__ = ('a',) # Error: not in a class body |
| 268 |
|
| 269 |
Acyclic classes |
| 270 |
--------------- |
| 271 |
|
| 272 |
By default, native classes participate in CPython's cyclic garbage |
| 273 |
collector (GC). This adds some overhead to object allocation and |
| 274 |
deallocation. If you know that instances of a class can never be |
| 275 |
part of reference cycles, you can opt out of cyclic GC using |
| 276 |
``@mypyc_attr(acyclic=True)``:: |
| 277 |
|
| 278 |
from mypy_extensions import mypyc_attr |
| 279 |
|
| 280 |
@mypyc_attr(acyclic=True) |
| 281 |
class Leaf: |
| 282 |
def __init__(self, x: int, name: str) -> None: |
| 283 |
self.x = x |
| 284 |
self.name = name |
| 285 |
|
| 286 |
This can improve performance, especially for classes that are |
| 287 |
allocated and deallocated frequently. Acyclic instances also use |
| 288 |
less memory, since CPython doesn't need to add a GC header to them. |
| 289 |
|
| 290 |
The acyclic property is not inherited by subclasses. Each subclass |
| 291 |
must explicitly use ``@mypyc_attr(acyclic=True)`` to also opt out |
| 292 |
of cyclic GC. |
| 293 |
|
| 294 |
.. warning:: |
| 295 |
|
| 296 |
If instances of an acyclic class actually participate in reference |
| 297 |
cycles, those cycles will never be collected, resulting in memory |
| 298 |
leaks. Only use this for classes whose instances won't refer back |
| 299 |
to objects that (directly or indirectly) refer to the instance. |
| 300 |
|
| 301 |
Other properties |
| 302 |
---------------- |
| 303 |
|
| 304 |
Instances of native classes don't usually have a ``__dict__`` attribute. |