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

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