2 ms·
One of my favorite parts of Python is the idempotent type casting functions. Say you have a function that takes a list as input, but sometimes a tuple is passe
by rectangletangle 8y ago
One of my favorite parts of Python is the idempotent type casting functions.
Say you have a function that takes a list as input, but sometimes a tuple is passed. Wrapping the input like lvalues = list(values), ensures that lvalues will always be a list (or it throws a type error), so you won't get annoying attribute errors, when trying to access the list's methods. In the case of a list type(list([])).__name__ == 'list', as does type(list(list([]))).__name__, etc.
This can get a bit tricky with situations where type casting may be undesirable, say casting a string to a list. So judicious use is necessary.