#!/usr/bin/env python # coding: utf-8 # # Modules # Open In Colab # # http://openbookproject.net/thinkcs/python/english3e/modules.html # - module is a file containing Python definitions and statements intended for use in other Python programs # - many Python modules come with built-in standard library # ## Various ways to import names into the current namespace # In[ ]: # import math module into the global namespace import math x = math.sqrt(100) print(x) # In[ ]: import random print(random.choice(list(range(1, 21)))) # In[ ]: from random import choice # In[ ]: print(choice([1, 2, 3, 4])) # In[ ]: help(math) # In[ ]: from math import * # Import all the identifiers from math print(sqrt(100)) print(pi) # In[ ]: from math import radians, sin rad = radians(90) print(rad) print(sin(rad)) # ## names can be imported to local namespace # In[ ]: def isUpper(letter): import string # string name is local return letter in string.ascii_uppercase # In[15]: print(isUpper('a')) # In[2]: # can we use string module outside isUpper function? print(string.digits) # ## scope and lookup rules #

The scope of an identifier is the region of program code in which the identifier can be accessed, or used.

# Three important scopes in Python: # - Local scope refers to identifiers declared within a function # - Global scope refers to all the identifiers declared within the current module, or file # - Built-in scope refers to all the identifiers built into Python -- those like range and min that are (almost) always available #

Precedence rule:

#
    #
  1. innermost or local scope
  2. #
  3. global scope
  4. #
  5. built-in scope
  6. #
# In[1]: def testLocalScope(): k = 5 for i in range(2): for j in range(2): if i == j: k = 3 print('inside=',k) print('outside=',k) # In[20]: test() # In[21]: print(k) # ## User-defined modules # #### use module1.py, module2.py inside modules folder to demonstrate user defined modules and importance of: # ```if __name__ == '__main__': # ... # ``` # # Packages # - folder with module(s) # - must define \__init\__.py empty module to initialize as package # - can't import package itself (in a useful way) but only module(s) or identifiers in the modules # - https://docs.python.org/3/tutorial/modules.html#packages # ## use fibos package to demostrate user-defined package # In[3]: import fibos # In[4]: help(fibos) # In[5]: fibos.fibo.fib(10) # In[6]: import fibos.fibo as f f.fib(10) # In[7]: from fibos import fibo fibo.fib(10) # In[ ]: