Namespaces: memory vs 'pollution'

Roel Schroeven roel at roelschroeven.net
Sun Jul 21 13:30:22 EDT 2019


DL Neil schreef op 21/07/2019 om 2:02:
> How do you remember to from-import- 'everything' that is needed?
> ... > Upon closer inspection, I realised it didn't just fail; it failed badly!
> Some silly, little, boy had imported the PythonEnvironment class but
> failed to ALSO import PythonVersionError. So, the reported error was not
> the expected exception!
> ...
> Is there some 'easy way' to make sure that one doesn't just import the
> desired class, but also remembers to import 'everything else' that might
> be necessary. In this case, it'd be rather nice to:
> 
> 	from environment_module import Python*
> 
> NB this is a syntax error, and won't import both the PythonEnvironment
> and PythonVersionError classes.
 > ...
> What do you do to (respecting purism) ensure 'everything' (necessary) is
> imported (and nothing more), preferably without relying upon (faulty, in
> my case) human-memory or reading through volumes of code/documentation?

This is one of the advantages of using import instead of from-import.

import environment_module

...
try:
     ....
     # Just an example, since I don't know PythonEnvironment
     env = environment_module.PythonEnvironment()
     ...
except environment_module.PythonVersionError:
     # Handle the exception

In this case you have a pretty long module name (by the way, you could 
probably shorten it by removing _module; there's normally no need to 
repeat it in the name of a module that it's a module), making repeating 
it everywhere somewhat awkward. You can import the module using another 
name to work around that:

import environment_module as envmod

...
try:
     ....
     # Just an example, since I don't know PythonEnvironment
     env = envmod.PythonEnvironment()
     ...
except envmod.PythonVersionError:
     # Handle the exception


-- 
"Honest criticism is hard to take, particularly from a relative, a
friend, an acquaintance, or a stranger."
         -- Franklin P. Jones

Roel Schroeven




More information about the Python-list mailing list