File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed 
python-tuts/0-beginner/8-Modules_Packages_Namespaces/Eg.3/B Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ # importer.py 
2+ print ('Running importer.py' )
3+ 
4+ import  os .path 
5+ import  types 
6+ import  sys 
7+ 
8+ 
9+ def  import_ (module_name , module_file , module_path ):
10+  if  module_name  in  sys .modules :
11+  return  sys .modules [module_name ]
12+ 
13+  module_rel_file_path  =  os .path .join (module_path , module_file )
14+  module_abs_file_path  =  os .path .abspath (module_rel_file_path )
15+ 
16+  # read source code from file 
17+  with  open (module_rel_file_path , 'r' ) as  code_file :
18+  source_code  =  code_file .read ()
19+ 
20+  # next we create a module object 
21+  mod  =  types .ModuleType (module_name )
22+  mod .__file__  =  module_abs_file_path 
23+ 
24+  # insert a reference to the module in sys.modules 
25+  sys .modules [module_name ] =  mod 
26+ 
27+  # compile the module source code into a code object 
28+  # optionally we should tell the code object where the source came from 
29+  # the third parameter is used to indicate that our source consists of a sequence of statements 
30+  code  =  compile (source_code , filename = module_abs_file_path , mode = 'exec' )
31+ 
32+  # execute the module 
33+  # we want the global variables to be stored in mod.__dict__ 
34+  exec (code , mod .__dict__ )
35+ 
36+  # return the module 
37+  return  sys .modules [module_name ]
                                 You can’t perform that action at this time. 
               
                  
0 commit comments