Created
May 20, 2020 13:51
-
-
Save bmispelon/4f0c961294a62d7f615a92239b4a0820 to your computer and use it in GitHub Desktop.
How to handle tuple creation in a generic way?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def my_tuple_function(t): | |
| """ | |
| Return a new tuple of the same length containing only zeroes. | |
| """ | |
| tuple_class = type(t) | |
| return tuple_class(*(0 for _ in t)) # works for namedtuple | |
| return tuple_class((0 for _ in t)) # works for plain tuple |
Author
The main reason I lean toward inspect is that once you inspect.signature the type, you can find out if certain argument sets would be legal to use when calling it.
Failing that, namedtuple classes all have the _make() method, and you can check for that. Which even simplifies your construction a bit:
def my_tuple_func(t):
tuple_type = type(t)
arg = (0 for _ in t)
return tuple_type._make(arg) if hasattr(tuple_type, '_make') else tuple_type(arg)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using the signature is pretty clever, I hadn't thought of that. I think it's the best solution as of yet in terms of being generic but I have to admit that this code makes me cry a little bit.
My real initial usecase involved
functools.singledispatchand I've learned since then that it's not possible to dispatch namedtuples separately from tuples. I think the hack I'll settle on is thehasattr(t, '_fields')and call it a day.