Skip to content

Commit 4a773d7

Browse files
committed
Document mypyc native_class flag
1 parent cef0275 commit 4a773d7

1 file changed

Lines changed: 41 additions & 1 deletion

File tree

CHANGELOG.md

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,47 @@ Contributed by Marc Mueller (PR [18641](https://github.com/python/mypy/pull/1864
8181

8282
### Annotating Native/Non-Native Classes in Mypyc
8383

84-
* Support for annotating classes to be native or not (native_class=True/False) (Valentin Stanciu, PR [18802](https://github.com/python/mypy/pull/18802))
84+
You can now declare a class as a non-native class when compiling with
85+
mypyc. Unlike native classes, which are extension classes and have an
86+
immutable structure, non-native classes are normal Python classes at
87+
runtime and are fully dynamic. Example:
88+
89+
```python
90+
from mypy_extensions import mypyc_attr
91+
92+
@mypyc_attr(native_class=False)
93+
class NonNativeClass:
94+
...
95+
96+
o = NonNativeClass()
97+
98+
# Ok, even if attribute "foo" not declared in class body
99+
setattr(o, "foo", 1)
100+
```
101+
102+
Classes are native by default in compiled modules, but classes that
103+
use certain features (such as most metaclasses) are implicitly
104+
non-native.
105+
106+
You can also explicitly declare a class as native. In this case mypyc
107+
will generate an error if it can't compile the class as a native
108+
class, instead of falling back to a non-native class:
109+
110+
```python
111+
from mypy_extensions import mypyc_attr
112+
from foo import MyMeta
113+
114+
# Error: Unsupported metaclass for a native class
115+
@mypyc_attr(native_class=True)
116+
class C(metaclass=MyMeta):
117+
...
118+
```
119+
120+
Since native classes are significantly more efficient that non-native
121+
classes, you may want to ensure that certain classes always compiled
122+
as native classes.
123+
124+
This feature was contributed by Valentin Stanciu (PR [18802](https://github.com/python/mypy/pull/18802)).
85125

86126
### Mypyc Fixes and Improvements
87127

0 commit comments

Comments
 (0)