-
-
Notifications
You must be signed in to change notification settings - Fork 30.9k
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
Argument names in __annotations__ are not mangled for functions defined inside class scope #64824
Comments
Assume I have this code: class Spam:
def eggs(__some_kwarg:int=None):
print(__some_kwarg) I can call Spam.bar with keyword arguments as expected from mangling: >>> Spam.eggs(10)
10
>>> Spam.eggs(_Spam__some_kwarg=10)
10 However, in the __annotations__ field, the argument name is not mangled: >>> Spam.eggs.__annotations__
{'__some_kwarg': <class 'int'>} This is an inconsistency which makes it difficult to work with function annotations in this case. |
It looks like it's a bug. Spam.eggs.__code__.co_varnames will have '_Spam__some_kwarg' as a name of the first parameter. So __annotations__ should have '_Spam__some_kwarg' instead of '__some_kwarg'. |
Furthermore: class Foo:
def bar(self, *, __kw:'anno'='default'):
pass >>> Foo.bar.__annotations__
{'__kw': 'anno'}
>>> Foo.bar.__kwdefaults__
{'_Foo__kw': 'default'} |
Patch is attached. Please review. |
Why would we mangle the names of arguments in the first place? What possible use case is there? |
The use case is multiple inheritance. You can define your methods with keyword and keyword-only params starting with '__', put in them some cached default for speeding up lookup time, and not being worried that someone can override the arg. The second reason is, I believe, is desire to be consistent with mangling methods and attributes. Again, using mangling for function arguments is, probably, not the best practice, and that, combined with the fact, that people are just starting to play with annotations, explains why this bug was so long unnoticed. But the semantics of arg names mangling is already there, implemented everywhere but __annotations__. The attached patch is fairly simple, and really is just a bug fix. It would be great if we can get this in 3.4 (and even in 3.3 and 3.2). |
(see review on rietveld) |
lgtm |
New changeset a63327162063 by Yury Selivanov in branch 'default': |
New changeset 5202aca8a673 by Victor Stinner in branch 'default': |
New changeset e301a515f8f4 by Benjamin Peterson in branch 'default': |
New changeset 4d7c3cbd8515 by Yury Selivanov in branch '3.4': New changeset 3bced76d2706 by Victor Stinner in branch '3.4': New changeset e5cde3fd7c74 by Benjamin Peterson in branch '3.4': |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: