How to structure Python code into modules / packages?

Suppose I have this barebones structure:

project/
  main.py
  providers/
    __init.py__
    acme1.py
    acme2.py
    acme3.py
    acme4.py
    acme5.py
    acme6.py

Suppose it main.pycontains (partial):

if complexcondition():
  print providers.acme5.get()

Where it is __init__.pyempty, but acme*.pycontains (partial):

def get():
  value=complexcalculation()
  return value

How to change these files to work?

Note. If the answer is "import acme1", "import acme2", etc. c __init__.py, is there a way to do this without manually listing them manually?

+3
source share
3 answers

This question asked today, Dynamically loading Python modules , should have your answer.

+3
source

! , ... , -.

/__ init __. py :

import os
import glob

module_path = os.path.dirname(__file__)
files = glob.glob(os.path.join(module_path, 'acme*.py'))
__all__ = [os.path.basename(f)[:-3] for f in files]

, /acme *.py

from providers import * main.py

+6

, , (, , ), , , __init__.py :

__all__ = ["acme1", "acme2", "acme3", "acme4", "acme5", "acme6"]

, , ... import *

from providers import *

, ,

acme1.get()
acme2.get()

If you have enough modules in the supplier package, which becomes a problem when filling out the list __all__, you may want to split them into smaller packages or save the data in a different way. I personally would not want to deal with dynamic importing schennagins every time I would like to reuse a package.

+5
source

Source: https://habr.com/ru/post/1706763/


All Articles