Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Do not use ClassVars with generic variables - #6348

Merged
JelleZijlstra merged 2 commits into
python:masterfrom
sobolevn:issue-6333
Nov 21, 2021
Merged

Do not use ClassVars with generic variables#6348
JelleZijlstra merged 2 commits into
python:masterfrom
sobolevn:issue-6333

Conversation

@sobolevn

@sobolevn sobolevn commented Nov 20, 2021

Copy link
Copy Markdown
Member

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
Copy Markdown
Contributor

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

@sobolevn

Copy link
Copy Markdown
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