Can global variable be passed into Python function?

Chris Angelico rosuav at gmail.com
Sat Mar 1 12:27:28 EST 2014


On Sun, Mar 2, 2014 at 4:07 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Sat, 01 Mar 2014 22:59:52 +1100, Chris Angelico wrote:
>> And, as proven here in this thread, you do not know what you are doing.
>
> Steady on, that's a bit harsh. In context, I think that Marko is assuming
> that the caller will only ever use the state values via their symbolic
> names, e.g. only refer to them as IDLE, CONNECTED etc. and never use
> their internal string values "IDLE", "CONNECTED".

A bit harsh, perhaps, but I stand by it: by repeatedly declaring that
something is safe when it has been proven not safe, he shows that he
does not know what he is doing - that he is not fully comprehending
the significance of object value vs identity as regards strings.

Incidentally, Python somewhat creates this issue, by sometimes
interning and sometimes not. (And the same with small integers,
although I've never heard the expression "int interning".) If strings
were always interned, then it would be obvious that identity and value
were one and the same. On the flip side, if a string literal always
created a new string (that is, if it were more like a "string
construction syntax" like square brackets for lists), then it would be
obvious that each one is a separate object. I don't say either option
is worth doing (especially the latter, O!), but by sometimes merging
and sometimes not, Python does slightly blur the line between identity
and value. (Obviously if strings were mutable, they'd *have* to have
separate identities.)

> I don't think that's a safe assumption, since it requires the caller to
> only ever do the right thing, but if it is true, then using "is" in the
> way he suggests cannot fail.

If you're depending on the caller doing the right thing, it's still
safe to use == rather than is. The only reason to use 'is' is to
prevent the caller from stuffing in some other string that happens to
be correct - hence his point about being able to change the keywords.
If the caller stuffs in the string "INIT" instead of the object
Foo.INIT, then "==" will happen to work until such time as Foo.INIT
becomes "INITIALIZING", at which point it breaks. Preventing that
means that unique object identity is crucial to the system working,
and that's pretty much impossible with strings. (I don't say it's
absolutely impossible; maybe if you intern some other string with the
same value, and then construct the string you want out of pieces, and
somehow prevent the compiler from figuring out what you're doing and
optimizing it all away, then maybe you could have something that
doesn't get reused anywhere else. But it's certainly not normal to be
able to be sure of that.)

ChrisA



More information about the Python-list mailing list