[Tutor] Wrapping with list

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Sep 13 13:18:30 CEST 2013


On 13 September 2013 11:24, Dotan Cohen <dotancohen at gmail.com> wrote:
> A function that I wrote works on a list or on a string. If the
> function is passed a string, then it wraps the string in a list at the
> top of the function. Is it bad form to wrap the sting in place?
>
> if not isinstance(someVar, list):
>     someVar = [someVar]
>
> To avoid that, I am creating a list then appending the original value:
>
> if not isinstance(someVar, list):
>     temp = someVar
>     someVar = []
>     someVar.append(temp)
>
> Is my prudence unwarrented?

Yes it is.

A simple assignment 'someVar = ...' does not modify the object that
the name 'someVar' previously referred to. The right hand side of the
assignment is evaluated producing an object and the name 'someVar' is
bound to the created object.

>>> a = 'asd'
>>> b = a
>>> a
'asd'
>>> b
'asd'
>>> b = 'qwe'
>>> a
'asd'
>>> b
'qwe'

Unless 'someVar' is declared global or nonlocal the name binding is
local to the function.

>>> def f(x):
...     x = 1
...
>>> a = 2
>>> a
2
>>> f(a)
>>> a
2
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

So the first form neither modifies the object in-place nor changes the
binding of any names outside the function. The tow forms you showed
above are equivalent except for the creation of the redundant name
'temp' that refers to the original argument passed to the function.

Compound assignments e.g. 'a += b' can sometimes modify the object
referred to by the name 'a' in-place if the object is mutable e.g. a
list:

>>> a = [1, 2, 3]
>>> b = a
>>> a
[1, 2, 3]
>>> b
[1, 2, 3]
>>> b += [4]
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4]
>>> b = b + [5]
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4, 5]

However, if 'a' is bound to an immutable object (such as a string)
then in-place modification is impossible and 'a += b' is equivalent to
'a = a + b'.

>>> s = 'qwe'
>>> s2 = s
>>> s
'qwe'
>>> s2
'qwe'
>>> s2 += 'zxc'
>>> s
'qwe'
>>> s2
'qwezxc'


Oscar


More information about the Tutor mailing list