Easy questions from a python beginner
Ethan Furman
ethan at stoneleaf.us
Wed Jul 14 12:06:34 EDT 2010
Alf P. Steinbach /Usenet wrote:
> * MRAB, on 12.07.2010 00:37:
>> Alf P. Steinbach /Usenet wrote:
>>>
>>> Of course there are variables, that's why the docs call them variables.
>>>
>> In Java a variable is declared and exists even before the first
>> assignment to it. In Python a 'variable' isn't declared and won't exist
>> until the first 'assignment' to it.
>
> That is a misconception.
>
> In Python a variable is declared by having an assignment to it, which
> for a local variable may be anywhere within a routine.
>
> If such a variable is used before it's been assigned to, then you get an
> uninitialized variable exception. Clearly the variable must exist in
> order for the exception to refer to it (not to mention the exception
> occurring at all).
Really? So it's impossible for the interpreter, upon seeing the name
'blah', to scan forward to see if 'blah' is somewhere in the function in
order to give a more meaningful error message? Of course not.
> def foo():
> print( blah )
> blah = "this is both an assignment and a declaration causing it to
> exist"
>
> foo()
>
> Clearly when the exception is raised, referring to the variable, the
> variable exists.
You are the only one spouting nonsense. Have you tried this?
--> def foo():
... print locals()
... blah = 'interesting'
... print locals()
...
--> foo()
{}
{'blah': 'interesting'}
As can be clearly seen, blah does not exist before the assignment -- the
*name* blah has not been *bound* to an object yet, which is also what
the error message says when you try to use it before it exists:
UnboundLocalError: local variable 'blah' referenced before assignment
Nothing religious about it -- just the facts.
~Ethan~
More information about the Python-list
mailing list