Imagine you had this code in python:
foo = MyObject()
fo.bar()
Obviously, we've got a typo and fo
should have been foo
. Right now python says:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'fo' is not defined
But with implicit class loading it might say:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named fo
which would be confusing. Worse yet, if you misspelled a variable name that just happened to be the name of a module, you would get an even more confusing error as you tried to treat that module as if it were your variable. Python can't tell whether something is a class name, object or whatever.
Java, on the other hand, I believe can tell from the syntax whether a certain identifier refers to a class or something else. Thus it has no problem with producing an appropriate error message.
Overall, it fits into the Python philosophy of being explicit rather then implicit. They figure its better to explicitly import a module rather than have it imported automatically. The error message issue is factor that plays into the decision.
Some have suggested that there would be a large runtime cost to implicit imports. I don't think so. What happens is something like this:
- LOAD_GLOBAL opcode invoked with name "foo"
- globals dictionary checked for "foo"
- builtins dictionary checked for "foo"
- If foo found, store in globals and continue on
- If foo not found, raise NameError
To support implicit module loading we could do:
- LOAD_GLOBAL opcode invoked with name "foo"
- globals dictionary checked for "foo"
- builtins dictionary checked for "foo"
- if the above fail, try
import foo
- If foo found, store in globals and continue on
- If foo not found, raise NameError
The first time the module is used, it would take a bit longer because it has to search through other dictionaries first. But that's only the first time, and shouldn't be significant in terms of whole program runtime.
There would be a significant cost, in the case of misspelled variable names. When they occour, python would waste time reading the disk trying to find the module. But if that happens your program is about to die with a traceback anyways and the performance isn't a big concern.