I don’t understand why python (at least 2.7) is not validating the exception handling mechanism for errors.
Example:
try:
some code selecting data from pymongo
except pymongo.errors.OperationFailure:
exception
In this case, if the exception is not called for the first time, python will not validate if I actually did import the pymongo lib.
Any idea why?
If I’m reading your question right, you want to know why
except pymongo.errors.OperationFailuredoesn’t cause an error when the module is loaded if you haven’t already imported thepymongomodule.Like most things in Python, the arguments to
exceptclauses are evaluated at runtime. In fact, they can be expressions! Python does not validate them at “compile” time any more than it validates any other names at that time.The reason is that Python is a dynamic language. Imports can be done conditionally, or performed based on names that are not known at “compile” time, and modules and other namespaces can be replaced, modified, or removed by code. As a result, Python literally cannot know whether
pymongo.errors.OperationFailureis a valid name at that point in your code’s execution without running your code.