Global variables and modules
Brian van den Broek
bvande at po-box.mcgill.ca
Fri Dec 24 17:15:18 CET 2004
Alex Martelli said unto the world upon 2004-12-24 03:23:
> <dkeeney at travelbyroad.net> wrote:
> If you really must, consider using a container object. The most
> suitable container object for these tasks is often a module. I.e.,
> code, in test1:
> import test2
> and then refer to test2.glbl throughout. I.e., forget 'from', use
> As I wrote in Python in a Nutshell, p. 120, last paragraph before
> "Module Loading":
> In general, the import statement is a better choice than the from
> statement. I suggest you think of the from statement [...] as [a]
> convenience meant only for occasional use in interactive Python
> sessions. If you always access module M with the statement import M,
> and always access M's attributes with explicit syntax M.A, your code
> will be slightly less concise, but far clearer and more readable.
> I don't know how I could have put this advice more strongly or more
> directly (I continue with explanations about the cases in which 'from'
> is instead appropriate, chiefly getting single modules from packages).
> Giving strong direct advice, rather than just reference info, in a book
> of the "in a Nutshell" series, is not common, but I do it quite a bit;
> after all, "how does Python work exactly", e.g. the fact that 'from X
> import Y' is almost the same as 'Y = X.Y', is pretty simple to explain,
> and so takes up little space -- OTOH, the consequences of this, such as
> "thus, generally, don't use 'from', use 'import'" may not be obvious to
> readers, so I point them out directly.
> Of course, that doesn't help much if people don't _read_ it;-).
I'm quite fond of the
import really_long_module_name as rlmn
idiom. I use it all the time for some utility modules that I have
developed, where I like the module to have a descriptive name, but I
don't feel like burning line-length on retyping it all the time. If you
adopt a standard set of abbreviations ('fu' for 'fileutils', etc.) you
get less typing while preserving the advantages of clarity and
readability that the unmodified import provides. (And, of course, both
protect your namespace from the clobbering that will eventually arise
with use of from.)
I don't think the relevant section of Nutshell mentions this idiom.
However, I don't have my copy with me (seasonal travel, and all), so
apologies if my memory leads me astray.
For what its worth, I'm glad for the advice in Nutshell. It transforms
the book from a useful thing for those who like dead-tree references
into a text one can actually read (as opposed to merely consult quickly).
Best to all,
More information about the Python-list