As powerful as Python is, it would be almost impossible to write meaningful code without importing certain modules.
Yes, handwritten code can sometimes replace information available in a module. For example, your code might contain the statement:
lower='abcdefghijklmnopqrstuvwxyz'
and your hand-written code is as good as:
lower=string.ascii_lowercase
In this situation you might decide that it's not necessary to import string.
But, what about a statement like:
error=sys.exc_info()
This statement provides essential information about the most recent error which execution of your code has caused.
Only an expert could create hand-written code to replace this statement and an expert would not want to do so.
When so many powerful features are available in python's modules, it makes good sense to use them.
With appropriate modules imported, your code reflects your good knowledge of python and your willingness to
reap the benefits of the labor of others whose contribution to python makes our professional lives easier.
You're already familiar with some of python's modules: decimal, sys.
In this lesson we'll look first at module string and the basic syntax concerning the use of module
string.
The values in the left hand column above are keys of dictionary globals() and they are always strings.
In the right hand column are the values associated with the keys of the left hand.
As you can see, the values may or may not be strings.
Because globals() is a dictionary, it may be accessed like a dictionary:
>>>[vforvinglobals()if'__'notinv]['ascii_letters','ascii_lowercase','ascii_uppercase','capwords','digits','hexdigits','octdigits','printable','punctuation','whitespace','Formatter','Template']# These values are the same as string.__all__ .>>>globals()['digits']'0123456789'>>>globals()['ascii_uppercase']'ABCDEFGHIJKLMNOPQRSTUVWXYZ'>>>
>>>capwords('the authOrizEd biogRAPHY of tHomas jeFferSON')'The Authorized Biography Of Thomas Jefferson'>>>>>>printable==digits+ascii_lowercase+ascii_uppercase+punctuation+whitespaceTrue>>>>>>dir(string._re)['A','ASCII','DEBUG','DOTALL','I','IGNORECASE','L','LOCALE','M','MULTILINE','RegexFlag','S','Scanner','T','TEMPLATE','U','UNICODE','VERBOSE','X','_MAXCACHE','__all__','__builtins__','__cached__','__doc__','__file__','__loader__','__name__','__package__','__spec__','__version__','_alphanum_bytes','_alphanum_str','_cache','_compile','_compile_repl','_expand','_locale','_pattern_type','_pickle','_subx','compile','copyreg','enum','error','escape','findall','finditer','fullmatch','functools','match','purge','search','split','sre_compile','sre_parse','sub','subn','template']>>>importre>>>>>>dir(re)['A','ASCII','DEBUG','DOTALL','I','IGNORECASE','L','LOCALE','M','MULTILINE','RegexFlag','S','Scanner','T','TEMPLATE','U','UNICODE','VERBOSE','X','_MAXCACHE','__all__','__builtins__','__cached__','__doc__','__file__','__loader__','__name__','__package__','__spec__','__version__','_alphanum_bytes','_alphanum_str','_cache','_compile','_compile_repl','_expand','_locale','_pattern_type','_pickle','_subx','compile','copyreg','enum','error','escape','findall','finditer','fullmatch','functools','match','purge','search','split','sre_compile','sre_parse','sub','subn','template']>>>>>>re==string._reTrue>>>
Note:
While the statement import * is convenient, Python's Documentation states:
In most cases Python programmers do not use this facility since it introduces an unknown set of names into the interpreter, possibly hiding some things you have already defined.
.... in general the practice of importing * from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions.
After you become familiar with the contents of module string, you may decide to import only the module
and use the syntax that requires the name of the module:
In this case we will be working with module decimal. If this module is new to you, spend some time looking at
module decimal as if it were module string above.
In the present working directory create a Python source file, for example, myDec.py . This will become module
myDec.
$python3.6Python3.6.3(v3.6.3:2c5fed86e0,Oct32017,00:32:08)[GCC4.2.1(AppleInc.build5666)(dot3)]ondarwinType"help","copyright","credits"or"license"formoreinformation.>>>>>>frommyDecimport*>>>globals(){'__name__':'__main__','__doc__':None,'__package__':None,'__loader__':<class'_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'decimal':<module'decimal'from'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/decimal.py'>,'D':<class'decimal.Decimal'>, 'getC':Context(prec=28,rounding=ROUND_HALF_EVEN,Emin=-999999,Emax=999999,capitals=1,clamp=0,flags=[],traps=[InvalidOperation,DivisionByZero,Overflow]),'T':<class'decimal.DecimalTuple'>, 'doit':<functiondoitat0x1018a1950>}>>>>>>decimal# Loaded from module myDec.<module'decimal'from'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/decimal.py'>>>>>>>dir(decimal)['BasicContext','Clamped','Context','ConversionSyntax','Decimal','DecimalException','DecimalTuple','DefaultContext','DivisionByZero','DivisionImpossible','DivisionUndefined','ExtendedContext','FloatOperation','HAVE_THREADS','Inexact','InvalidContext','InvalidOperation','MAX_EMAX','MAX_PREC','MIN_EMIN','MIN_ETINY','Overflow','ROUND_05UP','ROUND_CEILING','ROUND_DOWN','ROUND_FLOOR','ROUND_HALF_DOWN','ROUND_HALF_EVEN','ROUND_HALF_UP','ROUND_UP','Rounded','Subnormal','Underflow','__builtins__','__cached__','__doc__','__file__','__libmpdec_version__','__loader__','__name__','__package__','__spec__','__version__','getcontext','localcontext','setcontext']>>>>>>Thevariouscontexts:>>>>>>type(decimal.BasicContext)<class'decimal.Context'>>>>>>>type(decimal.DefaultContext)<class'decimal.Context'>>>>>>>type(decimal.ExtendedContext)<class'decimal.Context'>>>>>>>type(decimal.getcontext)<class'builtin_function_or_method'>>>>type(decimal.getcontext())<class'decimal.Context'>>>>>>>T<class'decimal.DecimalTuple'>>>>D<class'decimal.Decimal'>>>>doit<functiondoitat0x1018a1950>>>>>>>getCContext(prec=28,rounding=ROUND_HALF_EVEN,Emin=-999999,Emax=999999,capitals=1,clamp=0,flags=[],traps=[InvalidOperation,DivisionByZero,Overflow])>>>>>>doit(7)Decimal('12')>>>>>>getC.prec=31>>>getCContext(prec=31,rounding=ROUND_HALF_EVEN,Emin=-999999,Emax=999999,capitals=1,clamp=0,flags=[],traps=[InvalidOperation,DivisionByZero,Overflow])# prec was changed to 31.>>>>>>getC.prec=28>>>D(1234567890123456789012345678901234567890)+0Decimal('1.234567890123456789012345679E+39')# Precision of 28.>>>>>>getC.prec=10>>>D(1234567890123456789012345678901234567890)+0Decimal('1.234567890E+39')# precision of 10>>>>>>getCContext(prec=10,rounding=ROUND_HALF_EVEN,Emin=-999999,Emax=999999,capitals=1,clamp=0,flags=[Inexact,Rounded],traps=[InvalidOperation,DivisionByZero,Overflow])# Precision of 10.>>>>>>T(1,(3,4,5,6),-3)DecimalTuple(sign=1,digits=(3,4,5,6),exponent=-3)>>>T(1,(3,4,5,6),-3).sign1>>>T(1,(3,4,5,6),-3).digits(3,4,5,6)>>>T(1,(3,4,5,6),-3).exponent-3>>>>>>D(T(1,(3,4,5,6),-3))Decimal('-3.456')
importdecimal# If module decimal was previously loaded, this statement is ignored.# If module decimal was not previously loaded, this statement is executed.# Same for 'import sys' below.importsys# Handy abbreviations:getC=decimal.getcontext()T=decimal.DecimalTuple# User-written function:defD(v1):'''This function converts value v1 to decimal object.If there is an error in conversion, this functionattempts to avoid introducing another error in the'except' clause by ensuring that module 'sys' isavailable. It was loaded above.'''ifisinstance(v1,decimal.Decimal):returnv1error=output=''try:output=decimal.Decimal(str(v1))except:error=sys.exc_info()[:2]iferror:print('myDec.D: error converting',str(v1)[:80],'to Decimal:')print(' ',error)returnNonereturnoutput
This example (on UNIX) shows how to access global variables across modules.
Create 2 files test1.py and test.py.
# test1.py
def test1_ReceiveGlobals(dict1) :
for v in dict1 :
globals()[v] = dict1[v]
def test1_SendGlobals() :
return globals()
# test.py
from test1 import *
def set_globals() :
t1 = (
('test1_23',67),
('test1_24',83),
('common_1',17), # This name is repeated below against "global".
('common_2',23), # This name is repeated below against "global".
)
dict1 = dict( t1 )
test1_ReceiveGlobals(dict1)
global test_46,test_47
global common_1,common_2 # These 2 names exist in "dict1" above.
test_46 = 79
test_47 = 41
common_1 = 'φιλοσοφοῦμεν ἄνευ μαλακίας.' # This name exists in "dict1" above.
common_2 = 'These are the times that ....' # This name exists in "dict1" above.
def print_globals() :
print ()
print ('globals():')
for v in [v for v in globals() if '__' not in v]:
print ('globals[{}] = {}'.format(v, globals()[v]))
test1_globals = test1_SendGlobals()
print ()
print ('test1_globals:')
for v in [v for v in test1_globals if '__' not in v]:
print ('test1_globals[{}] = {}'.format(v, test1_globals[v]))
print_globals()
set_globals()
print_globals()
# file sout
globals():
globals[test1_ReceiveGlobals] = <function test1_ReceiveGlobals at 0x1022451e0> # Common to both.
globals[test1_SendGlobals] = <function test1_SendGlobals at 0x102245268> # Common to both.
globals[set_globals] = <function set_globals at 0x100561e18> # Unique to test.
globals[print_globals] = <function print_globals at 0x1022452f0> # Unique to test.
test1_globals:
test1_globals[test1_ReceiveGlobals] = <function test1_ReceiveGlobals at 0x1022451e0> # Common to both.
test1_globals[test1_SendGlobals] = <function test1_SendGlobals at 0x102245268> # Common to both.
globals():
globals[test1_ReceiveGlobals] = <function test1_ReceiveGlobals at 0x1022451e0> # Common to both.
globals[test1_SendGlobals] = <function test1_SendGlobals at 0x102245268> # Common to both.
globals[set_globals] = <function set_globals at 0x100561e18> # Unique to test.
globals[print_globals] = <function print_globals at 0x1022452f0> # Unique to test.
globals[test_46] = 79 # Unique to test.
globals[test_47] = 41 # Unique to test.
globals[common_1] = φιλοσοφοῦμεν ἄνευ μαλακίας. # Name exists in test1 below. Value is different.
globals[common_2] = These are the times that .... # Name exists in test1 below. Value is different.
test1_globals:
test1_globals[test1_ReceiveGlobals] = <function test1_ReceiveGlobals at 0x1022451e0> # Common to both.
test1_globals[test1_SendGlobals] = <function test1_SendGlobals at 0x102245268> # Common to both.
test1_globals[test1_23] = 67 # Unique to test1.
test1_globals[test1_24] = 83 # Unique to test1.
test1_globals[common_1] = 17 # Name exists in test above. Value is different.
test1_globals[common_2] = 23 # Name exists in test above. Value is different.
$ python3.6 ./main5.py
Traceback (most recent call last):
File "./main5.py", line 6, in <module>
test5.test5_doit()
File "...../test5.py", line 2, in test5_doit
main5_doit()
NameError: name 'main5_doit' is not defined
$
In the output of dir(string) are two names 'Formatter' and 'Template'. Because this page is about modules generally,
and module string is used as an example, there has been no information presented concerning these two classes.
For more information about these classes, see
"Custom String Formatting" and
"Template strings."
Experiment with statements such as import decimal, from decimal import *, import myDec,
from myDec import *.
Become familiar with the syntax associated with contents of modules, such as:
Decimal(6), decimal.Decimal(6), myDec.decimal.Decimal(6), D(6),
myDec.D(6).
Experiment with files main.py, test1.py, test2.py, test3.py. In main.py include statements import test1, import test2, import test3. Implement functionality so that code in test1 can invoke functions in test2 and test3, and vice-versa.