Skip to content

NamedTuples defined via Python 3.6 variable annotations should allow methods #352

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

Closed
roganov opened this issue Jan 13, 2017 · 7 comments
Closed

Comments

@roganov
Copy link
Contributor

roganov commented Jan 13, 2017

Following code should work as expected

In [1]: from typing import NamedTuple

In [2]: class X(NamedTuple):
   ...:     x: int
   ...:     def double(self):
   ...:         return 2 * x
   ...:     

In [3]: X(1).double()

At the moment it throws AttributeError as there is no double method on the constructed namedtuple.

The workaround is to define methods on subclass and set __slots__ = (). But unless I'm missing something, there is no reason why methods shouldn't work as expected.

@ilevkivskyi
Copy link
Member

Initially I implemented this syntax to mimic the old namedtuple API. But now I looks like there will be no problem allowing arbitrary methods (also in mypy).

@gvanrossum what do you think?

@gvanrossum
Copy link
Member

gvanrossum commented Jan 13, 2017 via email

@ilevkivskyi
Copy link
Member

@roganov Please check that you are happy with PR #362.

@roganov
Copy link
Contributor Author

roganov commented Jan 22, 2017

@ilevkivskyi Seems fine, thank you!

@ambv ambv closed this as completed in #362 Jan 23, 2017
@ambv
Copy link
Contributor

ambv commented Jan 23, 2017

Well, still needs typing to be synchronized with the CPython repo.

@ambv ambv reopened this Jan 23, 2017
@gvanrossum
Copy link
Member

Done. (Normally we don't keep issues open once the fix is committed to master.)

@ilevkivskyi
Copy link
Member

I have made a small follow-up PR #364
It adjusts the behaviour in case of a collision between a method name and NamedTuple field or special attribute. Now such method is silently ignored, but I think it is better to be "loud" here and raise an AttributeError (to avoid hiding obscure bugs):

class X(NamedTuple):
    x: int
    def _fields(self):  # This will be an error
        ...

@gvanrossum If you are not against this, then I will merge it tomorrow.

gvanrossum pushed a commit to python/mypy that referenced this issue May 16, 2017
This is the mypy implementation of python/typing#352.

Also fixes #3075.
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

No branches or pull requests

4 participants