Reputation: 159
I don't quite understand how this piece of code works:
def sequence_class(immutable):
return tuple if immutable else list
seq = sequence_class(immutable=False)
s = seq("Nairobi")
s
['N', 'a', 'i', 'r', 'o', 'b', 'i']
seq = sequence_class(immutable=True)
s = seq("Nairobi")
s
('N', 'a', 'i', 'r', 'o', 'b', 'i')
It is quite obvious what it is doing, but I don't understand how the function can magically return the tuple("Nairobi")
or list("Nairobi")
just with the statement return tuple if mutable else list
and without any parameter to the function.
Any clear explanation to this?
Upvotes: 2
Views: 84
Reputation: 1124538
Everything in Python is an object; the tuple
and list
objects are no exception.
The function simply returns a reference to either the tuple
or the list
object, based on the immutable
flag:
>>> def sequence_class(immutable):
... return tuple if immutable else list
...
>>> sequence_class(True)
<class 'tuple'>
>>> sequence_class(False)
<class 'list'>
You then bind seq
to that object, and calling seq
then calls the referenced type:
>>> seq = sequence_class(True)
>>> seq
<class 'tuple'>
>>> seq('abc')
('a', 'b', 'c')
You can do the same by directly assigning tuple
or list
to a variable, it just creates another reference to the same object:
>>> foo = list
>>> foo
<class 'list'>
>>> foo('abc')
['a', 'b', 'c']
Upvotes: 5
Reputation: 23098
Calling sequence_class
is exactly as if you did:
# if immutable == True
seq = tuple('Nairobi')
# if immutable == False
seq = list('Nairobi')
You just happened to replace tuple
or list
with the sequence_class()
function, which returns tuple
or list
based on the argument you provide.
Each time you call sequence_class()
, this expression is replaced with the value it returns.
Upvotes: 0