Skip to content

Commit

Permalink
Added __init__.py generation to subfolders to prevent errors when the…
Browse files Browse the repository at this point in the history
…y are imported again.
  • Loading branch information
Candoran2 committed Sep 18, 2021
1 parent 774d7aa commit e7bdd73
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
12 changes: 12 additions & 0 deletions codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,17 @@ def copy_src_to_generated():
copy_tree(src_dir, trg_dir)


def create_inits():
"""Create a __init__.py file in all subdirectories that don't have one, to prevent error on second import"""
base_dir = os.path.join(os.getcwd(), 'generated')
init_file = "__init__.py"
for root, dirs, files in os.walk(base_dir):
if init_file not in files:
# __init__.py does not exist, create it
with open(os.path.join(root, init_file), 'x'): pass
# don't go into subdirectories that start with a double underscore
dirs[:] = [dirname for dirname in dirs if dirname[:2] != '__']

def generate_classes():
logging.info("Starting class generation")
cwd = os.getcwd()
Expand All @@ -215,6 +226,7 @@ def generate_classes():
logging.info(f"Reading {format_name} format")
xmlp = XmlParser(format_name)
xmlp.load_xml(xml_path)
create_inits()


generate_classes()
12 changes: 6 additions & 6 deletions codegen/Module.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ def read(self, element):
self.custom = bool(eval(element.attrib.get("custom","true").replace("true","True").replace("false","False"),{}))

def write(self, rel_path):
file = open(os.path.join(os.getcwd(), "generated", rel_path, "__init__.py"), "w", encoding=self.parser.encoding)
file.write(self.comment_str)
file.write(f'\n\n__priority__ = {repr(self.priority)}')
file.write(f'\n__depends__ = {repr(self.depends)}')
file.write(f'\n__custom__ = {repr(self.custom)}')
file.write(f'\n')
with open(os.path.join(os.getcwd(), "generated", rel_path, "__init__.py"), "w", encoding=self.parser.encoding) as file:
file.write(self.comment_str)
file.write(f'\n\n__priority__ = {repr(self.priority)}')
file.write(f'\n__depends__ = {repr(self.depends)}')
file.write(f'\n__custom__ = {repr(self.custom)}')
file.write(f'\n')

0 comments on commit e7bdd73

Please sign in to comment.