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
No way to find out if an object is an instance of a namedtuple #52044
Comments
Apologies if there is a way of doing this, but I haven't been able to find anything. I need to be able to do the following: my_tuple = namedtuple("my_tuple", "a b c")
obj = my_tuple(1,2,3)
if isinstance(obj, namedtuple):
.. do stuff .. The best I could come up with for the moment is: if isinstance(obj, tuple) and type(obj) is not tuple:
.. do stuff .. |
In this case, what is wrong with: if isinstance(obj, my_tuple): ... or do you want to catch all namedtuples? And if so, why? (I suppose it would be easy to make all namedtuples inherit from a common base class, though) |
Hello namedtuple is a factory function, not a class (as hinted by the naming in lower case, see PEP 8), so there are no instances of namedtuple. You can workaround that with issubclass, or checking for special namedtuples attributes (_asdict, _replace, but this is fragile), or just not use class cheking, often unneeded in Python code. Kind regards |
Hi Antoine and Eric, Thanks for your responses. I need to be able to catch all named tuples, I don't know in advance what instance of a namedtuple it might be, but I want my function to only accept named tuples. Is this unreasonable? (I am actually writing a C interface which does conversion from namedtuples to a form of "RecordSpecification" to do with databases. The namedtuple is arbitrarily created by the user.) |
I don't know. Why exactly don't you want to accept something else? |
In this case, I need to have names for each object. It is also desirable to use the namedtuple because of their lightweight nature. If they were to subclass the namedtuple I would be happy to accept that, but I really do want them to pass some form of namedtuple to me, to have some sort of consistency. The named tuple gives an obvious simple interface for determining which fields are available and the order they are in. |
It seems a perfect case for "duck typing" style of programming:
|
Hi Amaury, Thanks. I had heard of but never bothered to read about duck-typing before now; though I have used it passively before. I think it does make sense in this case. I can't imagine any case where checking for the _fields attribute would fail and isinstance(x, namedtuple) would not. Besides which, for my current project I am forced to implement such a "workaround" anyway, so it doesn't affect me as such. The only reason that remains why I would want it is that I often use isinstance(x, Y) to deal with different Ys, and that was the thing I intuitively wanted to use in this case as a python programmer for quite a few years now. This is probably a pretty weak reason, so I am happy to close this issue if the consensus points to duck typing. |
For more discussion on this, see http://stackoverflow.com/questions/2166818 |
Discussed this with GvR. For 2.6 and 3.1 which are already released, check for the _fields attribute. This is a guaranteed part of the API is not fragile. For the C structures, check for the n_fields attribute. In the future, the C API needs to grow to match the namedtuple() API and we should add an abstract base class describing the common API. Then you'll be able to write: |
Am deferring this to Py3.3. There is a workaround available just using duck-typing and I would like to wait until more more has been done on StructSeq before setting committing to an new namedtuple Abstract Base Class (one released, it would be very hard to change). Also, I would like to see how pprint() evolves (because it may also want to have special handling for named tuples). |
To make sure I understand: StructSeq is the C-pendent of named tuples, and a NamedTuple ABC would have to work with StructSeqs too? |
On python-ideas I have proposed an ABC being also a kind of a mix-in, potentially making namedtuple subclassing (with custom methods etc.) more convenient, e.g.: class MyRecord(namedtuple.abc):
_fields = 'x y z'
def _my_custom_method(self):
return list(self._asdict().items()) or class MyAbstractRecord(namedtuple.abc):
def _my_custom_method(self):
return list(self._asdict().items())
class AnotherAbstractRecord(MyAbstractRecord):
def __str__(self):
return '<<<{}>>>'.format(super().__str__())
class MyRecord2(MyAbstractRecord):
_fields = 'a, b'
class MyRecord3(AnotherAbstractRecord):
_fields = 'p', 'q', 'r' Here is an experimental monkey-patcher adding the 'abc' attribute to namedtuple: I am not sure if it is worth preparing an actual patch based on it. If you think it is I could prepare one. |
PS. Newer, shorter version: http://dpaste.org/2aiQ/ |
Thanks for working on this. I have some remarks:
|
Thank you. Raymond is against the idea so I don't know if it makes sense to create the real patch for now (it would patch the collections module and, I suppose, addming tests, docs etc.). Anyway, if somebody would be interested in the idea, the newest version of the draft is here: http://dpaste.org/qyKv/. |
PS. For the record: the final recipe is here: http://code.activestate.com/recipes/577629-namedtupleabc-abstract-base-class-mix-in-for-named/ |
New changeset 7aa3f1f7ac94 by Raymond Hettinger in branch '3.2': New changeset 330d3482cad8 by Raymond Hettinger in branch 'default': |
Detecting _fields is the simplest thing we can do right now. There are too many structseq API differences to warrant bringing them under a single ABC umbrella. |
It may not enough, but the use of namedtuples (vs. plain tuples) with functools.singledispatch() would be messier without a NamedTuple ABC (or other base type). Of course, when would you want to dispatch specifically on namedtuple? I can think of a few relatively weak uses, but not enough to justify the cost of establishing a common base class for namedtuple. |
A NamedTuple ABC doesn't have to define any API (so that part could wait?)[1]. I see it as most useful for isinstance checks. Here's a solution along those lines: class NamedTuple(Sequence):
@classmethod
def __subclasshook__(cls, C):
if cls is NamedTuple:
if any("_fields" in B.__dict__ for B in C.__mro__):
return True
return NotImplemented
def namedtuple(...):
...
NamedTuple.register(result)
return result (or include NamedTuple in the bases in the template) For structseq support: class NamedTuple(Sequence):
@classmethod
def __subclasshook__(cls, C):
if cls is NamedTuple:
if any("_fields" in B.__dict__ or # for namedtuple
"n_fields" in B.__dict__ # for structseq
for B in C.__mro__):
return True
return NotImplemented [1] I agree there is still a problem if we define an ABC here with no API and then add some later. Then classes that inherit from NamedTuple would break later when we add an API (just |
I believe the structseq issues are a lot easier to solve than the appear. See bpo-20230, which adds a _fields member to every structseq type. Having done that, a NamedTuple ABC works on them just fine. And of course duck typing them without an ABC does too. |
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: