Question

What would this piece of code do and what is the role of sys.modules here?:

this_dir = os.path.dirname(__file__) 
dir_list = (x for x in os.listdir(this_dir) if os.path.isdir(os.path.join(this_dir, x)))

for dirpath in dir_list:
    if dirpath not in project_path:
        project_path.append(os.path.join(this_dir, dirpath))
setattr(sys.modules[__name__], '__path__', project_path)
Was it helpful?

Solution

This code adds all sub directories under current directory (from where script is running) to the path so that any modules can be loaded from it's sub-directories.

import os,sys
this_dir = os.path.dirname(__file__)  #get the current directory of running script
dir_list = (x for x in os.listdir(this_dir) if os.path.isdir(os.path.join(this_dir, x)))     #get the list of directories under current directory 
project_path = []
for dirpath in dir_list:   
    if dirpath not in project_path:
        project_path.append(os.path.join(this_dir, dirpath))
setattr(sys.modules[__name__], '__path__', project_path) #add to sys modules so any modules can be imported from thsi directories
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top