-
-
Save bmispelon/4f0c961294a62d7f615a92239b4a0820 to your computer and use it in GitHub Desktop.
| 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 |
The above is likely insufficient for what you're trying to do, but I think in general the
inspectmodule is where you want to be -- what you really care about is not the type oft, but figuring out the argument signature to create additional instances of the type oft.
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.singledispatch and 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 the hasattr(t, '_fields') and call it a day.
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)
The above is likely insufficient for what you're trying to do, but I think in general the
inspectmodule is where you want to be -- what you really care about is not the type oft, but figuring out the argument signature to create additional instances of the type oft.