simultaneous assignment

Diez B. Roggisch deets at nospam.web.de
Tue May 2 19:08:01 CEST 2006


John Salerno wrote:

> Is there a way to assign multiple variables to the same value, but so
> that an identity test still evaluates to False?
> 
> e.g.:
> 
>  >>> w = x = y = z = False
>  >>> w
> False
>  >>> x
> False
>  >>> w == x
> True
>  >>> w is x
> True         # not sure if this is harmful
> 
> The first line above is the only way I know to do it, but it seems to
> necessarily lead to the true identity test.

Yes, and there is no way around that - given that python has not an
overloadable assignment operator as e.g. C++ offers (praise the BDFL!). The
semantics of what looks like assignment in python is "I've got a fancy
object somewhere, and now I want to be able to refer to it by that nice
name here". Actually things are somewhat more complicated in case of
list/dictionary element assignment, but for your case that is irrelevant.

Besides, depending on what you assign (e.g. integers, as well as the boolean
constants I guess) you might not even have the choice to guarantee how the
identity test results anyway. Consider this:

>>> a = 1000000
>>> b = 1000000
>>> a is b
False
>>> a = 100
>>> b = 100
>>> a is b
False
>>> a = 10
>>> b = 10
>>> a is b
True
>>>

I can't imagine what you're actually after here, but assuming that you
really need this and that we're talking "real" objects here, sequence
unpacking and assignment might come handy here, together with a small
list-comp:

a, b, c = [copy.copy(o) for i in xrange(3)]


Diez



More information about the Python-list mailing list