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.

Generally, forward references are only a concern in top-level module code that executesimmediately; functions can reference names arbitrarily. Here’s an example thatillustrates forward reference:func1( )# Error: "func1" not yet assigneddef func1( ):print func2( ) # OK: "func2" looked up laterfunc1( )# Error: "func2" not yet assigneddef func2( ):return "Hello"func1( )# Okay: "func1" and "func2" assignedWhen this file is imported (or run as a standalone program), <strong>Python</strong> executes itsstatements from top to bottom. The first call to func1 fails because the func1 defhasn’t run yet. The call to func2 inside func1 works as long as func2’s def has beenreached by the time func1 is called (it hasn’t when the second top-level func1 call isrun). The last call to func1 at the bottom of the file works because func1 and func2have both been assigned.Mixing defs with top-level code is not only hard to read, it’s dependent on statementordering. As a rule of thumb, if you need to mix immediate code with defs, putyour defs at the top of the file, and top-level code at the bottom. That way, yourfunctions are guaranteed to be defined and assigned by the time code that uses themruns.Importing Modules by Name StringThe module name in an import or from statement is a hardcoded variable name.Sometimes, though, your program will get the name of a module to be imported as astring at runtime (e.g., if a user selects a module name from within a GUI). Unfortunately,you can’t use import statements directly to load a module given its name as astring—<strong>Python</strong> expects a variable name here, not a string. For instance:>>> import "string"File "", line 1import "string"^SyntaxError: invalid syntaxIt also won’t work to simply assign the string to a variable name:x = "string"import xHere, <strong>Python</strong> will try to import a file x.py, not the string module.438 | Chapter 21: Advanced Module Topics

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

Saved successfully!

Ooh no, something went wrong!