60 likes | 263 Views
Modules. Module. Collection of functions and global variables Stores in a single file Named with . py extension. Using Your Module. import <filename> Do not include extension . py in filename Access function in module: <filename>.< function_name >(< argument_list >)
E N D
Module • Collection of functions and global variables • Stores in a single file • Named with .py extension
Using Your Module • import <filename> • Do not include extension .py in filename • Access function in module: • <filename>.<function_name>(<argument_list>) • Access global variable from module: • <filename>.<variable_name>
Gotchas • Any statements that are not in a function in the imported module will be executed when the module is imported. • Be careful with circular imports • A imports B and B imports A. • Will mostly likely result in an error
Dividing Code over Modules • A module contains functions that are closely related • random • grid • math • Etc • Avoid global variables in modules • Anyone can change the value of the variable!
Alternate Forms for Import • Standard way to import: • import <filename> • x = random.randint(1,3) • Importing a function (or variable) • from random import randint • x = randint(1,3) • Importing entire module avoids naming conflicts • Importing function (or variable) makes code that uses function simpler to read