Reputation: 1
I wrote a small program in sample.py file,
a=6
def f1():
a=3
return f2()
#def f2(): commented intentionally
# b = a*a
# return b
and loaded as __main__
module using command
>>>python -i sample.py
But i see that interpreter does not check the binding of f2 during loading of module.
Interpreter only realises that f2 name is not binded to its value when i call
>>>f1()
Another example, where interpreter checks the binding of name big1
, while loading the file as __main__
module using command >>>python -i sample.py
throws an error saying big1 is not defined
big, small = 3, -4
while big > 2 or small < -2:
big, small = -small - 1, -big + 1
print(big1)
My question is:
1)
Why python interpreter does not take an effort to check whether all names are bind during loading of sample.py file as __main__
module and defer to using that name f1()
?
2) Do you think large projects will create complexity, Because the test cases written must make sure each name
is used for testing before it goes for production?
Upvotes: 2
Views: 94
Reputation: 6488
Consider this example:
def f1():
name = raw_input()
exec "def {}(): print 'I am a function'".format(name)
f2()
If a user enters "f2"
when prompted, then f2()
will execute correctly, but not otherwise.
This is a perfectly legal python program, and the line f2()
may or may not execute correctly, dependent completely on user input. So python cannot determine at module load time whether execution of this code will result in a name error or not.
Addressing some additional confusion:
It might seem that python does sometimes do static name-checking. Ie, if we have file1.py
:
def foo():
print x1
and you do python file1.py
, no error will be printed. The function foo
has been defined, but not run. We could also do python -i file1.py
, which will open up an interpreter. If in the interpreter we then type foo()
, now the code will run, and we'll get the lookup error for x1
.
Consider a second file file2.py
:
print x1
Here, there is no function being defined. We're simply running a print
statement at the top-level. Doing python file2.py
will cause a lookup error for x1
, since running file2.py
constitutes actually running that print statement, as opposed to only defining a function that would run the print statement when called.
So it's not that python sometimes does static name-checking -- python will only throw a name error when code involving that name is actually run. It's just that when code gets run depends on where it is (in a function vs being top-level).
Upvotes: 4