Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Do not use ClassVars with generic variables #6348

Merged
merged 2 commits into from
Nov 21, 2021
Merged

Do not use ClassVars with generic variables #6348

merged 2 commits into from
Nov 21, 2021

Conversation

sobolevn
Copy link
Member

@sobolevn sobolevn commented Nov 20, 2021

There are two changes:

  1. pointer
  2. Array

But, they are different. Let's see why.

pointer

Docs: https://docs.python.org/3/library/ctypes.html#ctypes.pointer

>>> from ctypes import pointer
>>> pointer._type_
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute '_type_'

>>> from ctypes import c_int
>>> i = c_int(1)
>>> pointer(i)._type_
<class 'ctypes.c_int'>

This looks like an instance attribute to me.

Array

Docs: https://docs.python.org/3/library/ctypes.html#ctypes.Array

>>> from ctypes import Array
>>> Array._type_
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object '_ctypes.Array' has no attribute '_type_'

In this case it is even more cryptic.
Array is not used directly most of the time as far as I know.

Moreover, Array is an abstract class in runtime (but not in typeshed).
I will open a new issue for this.

Docs suggest to follow this practice to create new Array subtypes:

>>> from ctypes import *
>>> class POINT(Structure):
...   _fields_ = ("x", c_int), ("y", c_int)
... 
>>> Arr = POINT * 3
>>> Arr._type_
<class '__main__.POINT'>
>>> Arr._length_
3
>>> type(Arr)
<class '_ctypes.PyCArrayType'>
>>> Arr
<class '__main__.POINT_Array_3'>

What really happens is we create a new type for each *, in this case: POINT_Array_3.

Closes #6333

@github-actions
Copy link
Contributor

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

@sobolevn
Copy link
Member Author

Thank you! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

ctypes/__init__.pyi uses TypeVar within ClassVar
2 participants