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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The main reason I lean toward
inspectis that once youinspect.signaturethe 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: