advanced programming techniques fh none tryfh open(filename" "encoding="utf "code fh read(module type(sys)(namesys modules[namemodule exec(codemodule __dict__modules append(moduleexcept (environmenterrorsyntaxerroras errsys modules pop(namenoneprint(errfinallyif fh is not nonefh close(return modules we begin by iterating over all the files in the program' directory if this is the current directoryos path dirname(__file__will return an empty string which would cause os listdir(to raise an exceptionso we pass if necessary for each candidate file (ends with py and contains the text "magic")we get the module name by chopping off the file extension if the name is valid identifier it is viable module nameand if it isn' already in the global list of modules maintained in the sys modules dictionary we can try to import it we read the text of the file into the code string the next linemodule type(sys)(name)is quite subtle when we call type(it returns the type object of the object it is given so if we called type( we would get int back if we print the type object we just get something human readable like "int"but if we call the type object as functionwe get an object of that type back for examplewe can get the integer in variable by writing or int( )or type( )( )or int_type type( ) int_type( in this case we've used type(sysand sys is moduleso we get back the module type object (essentially the same as class object)and can use it to create new module with the given name just as with the int example where it didn' matter what integer we used to get the int type objectit doesn' matter what module we use (as long as it is one that existsthat ishas been importedto get the module type object once we have new (emptymodulewe add it to the global list of modules to prevent the module from being accidentally reimported this is done before calling exec(to more closely mimic the behavior of the import statement then we call exec(to execute the code we have read--and we use the module' dictionary as the code' context at the end we add the module to the list of modules we will pass back and if problem ariseswe delete the module from the global modules dictionary if it has been added--it will not have been added to the list of modules if an error occurred notice that exec(can handle any