Skip to content

Instantly share code, notes, and snippets.

@bmispelon
Created May 20, 2020 13:51
Show Gist options
  • Select an option

  • Save bmispelon/4f0c961294a62d7f615a92239b4a0820 to your computer and use it in GitHub Desktop.

Select an option

Save bmispelon/4f0c961294a62d7f615a92239b4a0820 to your computer and use it in GitHub Desktop.
How to handle tuple creation in a generic way?
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
@ubernostrum
Copy link

The above is likely insufficient for what you're trying to do, but I think in general the inspect module is where you want to be -- what you really care about is not the type of t, but figuring out the argument signature to create additional instances of the type of t.

@bmispelon
Copy link
Author

The above is likely insufficient for what you're trying to do, but I think in general the inspect module is where you want to be -- what you really care about is not the type of t, but figuring out the argument signature to create additional instances of the type of t.

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.

@ubernostrum
Copy link

ubernostrum commented May 20, 2020

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