native_classes.rst 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. By default, a non-native class can't inherit a native class, and you
  50. can't inherit from a native class outside the compilation unit that
  51. defines the class. You can enable these through
  52. ``mypy_extensions.mypyc_attr``::
  53. from mypy_extensions import mypyc_attr
  54. @mypyc_attr(allow_interpreted_subclasses=True)
  55. class Cls:
  56. ...
  57. Allowing interpreted subclasses has only minor impact on performance
  58. of instances of the native class. Accessing methods and attributes of
  59. a *non-native* subclass (or a subclass defined in another compilation
  60. unit) will be slower, since it needs to use the normal Python
  61. attribute access mechanism.
  62. You need to install ``mypy-extensions`` to use ``@mypyc_attr``:
  63. .. code-block:: text
  64. pip install --upgrade mypy-extensions
  65. Class variables
  66. ---------------
  67. Class variables must be explicitly declared using ``attr: ClassVar``
  68. or ``attr: ClassVar[<type>]``. You can't assign to a class variable
  69. through an instance. Example::
  70. from typing import ClassVar
  71. class Cls:
  72. cv: ClassVar = 0
  73. Cls.cv = 2 # OK
  74. o = Cls()
  75. print(o.cv) # OK (2)
  76. o.cv = 3 # Error!
  77. Generic native classes
  78. ----------------------
  79. Native classes can be generic. Type variables are *erased* at runtime,
  80. and instances don't keep track of type variable values.
  81. Compiled code thus can't check the values of type variables when
  82. performing runtime type checks. These checks are delayed to when
  83. reading a value with a type variable type::
  84. from typing import TypeVar, Generic, cast
  85. T = TypeVar('T')
  86. class Box(Generic[T]):
  87. def __init__(self, item: T) -> None:
  88. self.item = item
  89. x = Box(1) # Box[int]
  90. y = cast(Box[str], x) # OK (type variable value not checked)
  91. y.item # Runtime error: item is "int", but "str" expected
  92. Metaclasses
  93. -----------
  94. Most metaclasses aren't supported with native classes, since their
  95. behavior is too dynamic. You can use these metaclasses, however:
  96. * ``abc.ABCMeta``
  97. * ``typing.GenericMeta`` (used by ``typing.Generic``)
  98. .. note::
  99. If a class definition uses an unsupported metaclass, *mypyc
  100. compiles the class into a regular Python class*.
  101. Class decorators
  102. ----------------
  103. Similar to metaclasses, most class decorators aren't supported with
  104. native classes, as they are usually too dynamic. These class
  105. decorators can be used with native classes, however:
  106. * ``mypy_extensions.trait`` (for defining :ref:`trait types <trait-types>`)
  107. * ``mypy_extensions.mypyc_attr`` (see :ref:`above <inheritance>`)
  108. * ``dataclasses.dataclass``
  109. Dataclasses have partial native support, and they aren't as efficient
  110. as pure native classes.
  111. .. note::
  112. If a class definition uses an unsupported class decorator, *mypyc
  113. compiles the class into a regular Python class*.
  114. Deleting attributes
  115. -------------------
  116. By default, attributes defined in native classes can't be deleted. You
  117. can explicitly allow certain attributes to be deleted by using
  118. ``__deletable__``::
  119. class Cls:
  120. x: int = 0
  121. y: int = 0
  122. other: int = 0
  123. __deletable__ = ['x', 'y'] # 'x' and 'y' can be deleted
  124. o = Cls()
  125. del o.x # OK
  126. del o.y # OK
  127. del o.other # Error
  128. You must initialize the ``__deletable__`` attribute in the class body,
  129. using a list or a tuple expression with only string literal items that
  130. refer to attributes. These are not valid::
  131. a = ['x', 'y']
  132. class Cls:
  133. x: int
  134. y: int
  135. __deletable__ = a # Error: cannot use variable 'a'
  136. __deletable__ = ('a',) # Error: not in a class body
  137. Other properties
  138. ----------------
  139. Instances of native classes don't usually have a ``__dict__`` attribute.