Scope
local and global concepts are used in the standard ways.
Variables, and nested functions which are created within a function for the first-time, can only be local and can only be used within those functions and inner nested functions. You can override that by creating a variable in a function using the global keyword. This is a rare case in python where a variable is actually declared without making an assignment to it.
food = "candy"
def runaway():
food = "nuts"
global drink
# incorrect putting: global drink = "water" all on one line
drink = "water"
runaway()
print(drink)
print(food)
# results in:
water
candy
Modules
Modules in python are like C libraries and with the ending of .py file extension
Optionally you can import a module_name with an alias on import which is good for when using modules of other people and you'd rather have them going by a different name to accommodate code that you've already written. Usually, but not necessarily, the alias is a shortened version of the module name. Note the new keyword as.
For example:
import module_name as jrq
You use jrq functions or variables within module_name in your own code.
jrq.eatfood() # a module function
jrq.hometown # a module property
There's a built-in function in Python which is dir() which lists all the functions or variables in a module.
listing = dir(module_name)
At a really fine grain level one can pick and choose which elements to import using the from import keyword combo but you're going to have to know the name of the variable (property) or the function in advance. Either that, or get it from a dir() call.
The format goes like this:
from module_name import function_name
from module_name import variable_name
If you do it this way you pick and choose functions and variables.
Don't use the module_name as a base on the function or variable calls; just use the function or variable name as if it were built in globally to your homegrown code.
from module_name import function_name
##### incorrect: module_name.function_name
function_name
To summarize:
1. Import a module by its normal given name, gets you all of the module's functions and properties. Use the module_name as a base when calling on the function or property.
import special_things
gift = special_things.box
2. Import a module and reassign it right away to an alias.
Use the Alias as the base when calling on the function or property.
import special_things as stuff
gift = stuff.box
3. Import just the function or property variable that you want. Do NOT use any module name or alias base for it.
from special_things import box
gift = box
No comments:
Post a Comment