AW: The rules of reference

Alex Martelli aleax at aleax.it
Thu Oct 31 15:15:17 EST 2002


Gerson Kurz wrote:
        ...
>     from a import *
        ...
> reimport a. That should work, right?

Wrong.  Rule of thumb: wnenever you see a statement of the form:
    from <wherever> import *
the smart bet is that things WON'T work.  If all Pythonistas
forgot suddenly about the existence of statement 'from', and
by the same magic all existing Python sources (including those
in printed form) were changed to use statement 'import' instead,
I think the average quality of Python code now existing and still
to be written in the future would be enhanced.


With that wretched from statement you did the equivalent of:

    import a as temporarynameotherwisenonexisting
    num = temporarynameotherwisenonexisting.num
    print_num = temporarynameotherwisenonexisting.print_num
    del temporarynameotherwisenonexisting

When you later bind something else to your num (__main__.num),
that binding has no effect whatsoever on the attribute similarly
named 'num' in other modules.

And the print_num's reference to its own global 'num' is to the
entry in print_num.func_globals['a'], of course.  I.e., it's in
another module, and any binding you may make or unmake to names
in module __main__ will not affect it.


Alex




More information about the Python-list mailing list