12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

If we use import to get the whole module, and then assign to a qualified name, however,we change the name in nested1.py. Qualification directs <strong>Python</strong> to a name inthe module object, rather than a name in the importer (nested3.py):import nested1nested1.X = 88nested1.printer( )# Get module as a whole# OK: change nested1's X% python nested3.py88from * Can Obscure the Meaning of VariablesI mentioned this in Chapter 19, but saved the details for here. Because you don’t listthe variables you want when using the from module import * statement form, it canaccidentally overwrite names you’re already using in your scope. Worse, it can makeit difficult to determine where a variable comes from. This is especially true if thefrom * form is used on more than one imported file.For example, if you use from * on three modules, you’ll have no way of knowingwhat a raw function call really means, short of searching all three external modulefiles (all of which may be in other directories):>>> from module1 import * # Bad: may overwrite my names silently>>> from module2 import * # Worse: no way to tell what we get!>>> from module3 import *>>> . . .>>> func( ) # Huh???The solution again is not to do this: try to explicitly list the attributes you want inyour from statements, and restrict the from * form to at most one imported moduleper file. That way, any undefined names must by deduction be in the module namedin the single from *. You can avoid the issue altogether if you always use importinstead of from, but that advice is too harsh; like much else in programming, from is aconvenient tool if used wisely.reload May Not Impact from ImportsHere’s another from-related gotcha: as discussed previously, because from copies(assigns) names when run, there’s no link back to the module where the names camefrom. Names imported with from simply become references to objects, which happento have been referenced by the same names in the importee when the from ran.Because of this behavior, reloading the importee has no effect on clients that importits names using from. That is, the client’s names will still reference the originalobjects fetched with from, even if the names in the original module are later reset:440 | Chapter 21: Advanced Module Topics

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!