native_classes.rst 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. .. _native-classes:
  2. Native classes
  3. ==============
  4. Classes in compiled modules are *native classes* by default (some
  5. exceptions are discussed below). Native classes are compiled to C
  6. extension classes, which have some important differences from normal
  7. Python classes. Native classes are similar in many ways to built-in
  8. types, such as ``int``, ``str``, and ``list``.
  9. Immutable namespaces
  10. --------------------
  11. The type object namespace of native classes is mostly immutable (but
  12. class variables can be assigned to)::
  13. class Cls:
  14. def method1(self) -> None:
  15. print("method1")
  16. def method2(self) -> None:
  17. print("method2")
  18. Cls.method1 = Cls.method2 # Error
  19. Cls.new_method = Cls.method2 # Error
  20. Only attributes defined within a class definition (or in a base class)
  21. can be assigned to (similar to using ``__slots__``)::
  22. class Cls:
  23. x: int
  24. def __init__(self, y: int) -> None:
  25. self.x = 0
  26. self.y = y
  27. def method(self) -> None:
  28. self.z = "x"
  29. o = Cls(0)
  30. print(o.x, o.y) # OK
  31. o.z = "y" # OK
  32. o.extra = 3 # Error: no attribute "extra"
  33. .. _inheritance:
  34. Inheritance
  35. -----------
  36. Only single inheritance is supported (except for :ref:`traits
  37. <trait-types>`). Most non-native classes can't be used as base
  38. classes.
  39. These non-native classes can be used as base classes of native
  40. classes:
  41. * ``object``
  42. * ``dict`` (and ``Dict[k, v]``)
  43. * ``BaseException``
  44. * ``Exception``
  45. * ``ValueError``
  46. * ``IndexError``
  47. * ``LookupError``
  48. * ``UserWarning``
  49. * ``typing.NamedTuple``
  50. * ``enum.Enum``
  51. By default, a non-native class can't inherit a native class, and you
  52. can't inherit from a native class outside the compilation unit that
  53. defines the class. You can enable these through
  54. ``mypy_extensions.mypyc_attr``::
  55. from mypy_extensions import mypyc_attr
  56. @mypyc_attr(allow_interpreted_subclasses=True)
  57. class Cls:
  58. ...
  59. Allowing interpreted subclasses has only minor impact on performance
  60. of instances of the native class. Accessing methods and attributes of
  61. a *non-native* subclass (or a subclass defined in another compilation
  62. unit) will be slower, since it needs to use the normal Python
  63. attribute access mechanism.
  64. You need to install ``mypy-extensions`` to use ``@mypyc_attr``:
  65. .. code-block:: text
  66. pip install --upgrade mypy-extensions
  67. Class variables
  68. ---------------
  69. Class variables must be explicitly declared using ``attr: ClassVar``
  70. or ``attr: ClassVar[<type>]``. You can't assign to a class variable
  71. through an instance. Example::
  72. from typing import ClassVar
  73. class Cls:
  74. cv: ClassVar = 0
  75. Cls.cv = 2 # OK
  76. o = Cls()
  77. print(o.cv) # OK (2)
  78. o.cv = 3 # Error!
  79. .. tip::
  80. Constant class variables can be declared using ``typing.Final`` or
  81. ``typing.Final[<type>]``.
  82. Generic native classes
  83. ----------------------
  84. Native classes can be generic. Type variables are *erased* at runtime,
  85. and instances don't keep track of type variable values.
  86. Compiled code thus can't check the values of type variables when
  87. performing runtime type checks. These checks are delayed to when
  88. reading a value with a type variable type::
  89. from typing import TypeVar, Generic, cast
  90. T = TypeVar('T')
  91. class Box(Generic[T]):
  92. def __init__(self, item: T) -> None:
  93. self.item = item
  94. x = Box(1) # Box[int]
  95. y = cast(Box[str], x) # OK (type variable value not checked)
  96. y.item # Runtime error: item is "int", but "str" expected
  97. Metaclasses
  98. -----------
  99. Most metaclasses aren't supported with native classes, since their
  100. behavior is too dynamic. You can use these metaclasses, however:
  101. * ``abc.ABCMeta``
  102. * ``typing.GenericMeta`` (used by ``typing.Generic``)
  103. .. note::
  104. If a class definition uses an unsupported metaclass, *mypyc
  105. compiles the class into a regular Python class*.
  106. Class decorators
  107. ----------------
  108. Similar to metaclasses, most class decorators aren't supported with
  109. native classes, as they are usually too dynamic. These class
  110. decorators can be used with native classes, however:
  111. * ``mypy_extensions.trait`` (for defining :ref:`trait types <trait-types>`)
  112. * ``mypy_extensions.mypyc_attr`` (see :ref:`above <inheritance>`)
  113. * ``dataclasses.dataclass``
  114. * ``@attr.s(auto_attribs=True)``
  115. Dataclasses and attrs classes have partial native support, and they aren't as
  116. efficient as pure native classes.
  117. .. note::
  118. If a class definition uses an unsupported class decorator, *mypyc
  119. compiles the class into a regular Python class*.
  120. Deleting attributes
  121. -------------------
  122. By default, attributes defined in native classes can't be deleted. You
  123. can explicitly allow certain attributes to be deleted by using
  124. ``__deletable__``::
  125. class Cls:
  126. x: int = 0
  127. y: int = 0
  128. other: int = 0
  129. __deletable__ = ['x', 'y'] # 'x' and 'y' can be deleted
  130. o = Cls()
  131. del o.x # OK
  132. del o.y # OK
  133. del o.other # Error
  134. You must initialize the ``__deletable__`` attribute in the class body,
  135. using a list or a tuple expression with only string literal items that
  136. refer to attributes. These are not valid::
  137. a = ['x', 'y']
  138. class Cls:
  139. x: int
  140. y: int
  141. __deletable__ = a # Error: cannot use variable 'a'
  142. __deletable__ = ('a',) # Error: not in a class body
  143. Other properties
  144. ----------------
  145. Instances of native classes don't usually have a ``__dict__`` attribute.