简体   繁体   English

Python从文件夹中导入所有内容

[英]Python import all from folder

I have encountered issue while working on my Django project.我在处理 Django 项目时遇到了问题。 I have multiple classes inside views.py.我在views.py中有多个类。 It had 1200 lines so I decided to move these views to seperated files inside new folder.它有 1200 行,所以我决定将这些视图移动到新文件夹中的单独文件中。 Now one files, for example Customer.py has 2 classes for different operations.现在一个文件,例如 Customer.py 有 2 个用于不同操作的类。

This is my project structure before splitting views.py:这是我在拆分views.py之前的项目结构:

MyProject
  core
    -  urls.py
  api
    -  views.py
  manage.py

Project structure after splitting views.py拆分views.py后的项目结构

MyProject
  core
    -  urls.py
  api
    -  view
        -   *all the files with multiple classes in each file*
  manage.py

After splitting views.py I needed to import all classes from all files inside of the view folder inside core/urls.py.拆分views.py 后,我需要从core/urls.py 中view 文件夹内的所有文件中导入所有类。 I have been trying to find out few hours now and can figure it out...我一直在尝试找出几个小时,并且可以弄清楚......

My current solution is that in urls.py im doing我目前的解决方案是在 urls.py 中

from api.view import * 

while having init .py inside view folder which is doing同时将init .py 放入正在执行的视图文件夹中

from .oneOfManyFiles import *

for all classes...对于所有课程...

I highly dont like this solution, I would love to find out some good looking simple elegant solution.我非常不喜欢这个解决方案,我很想找到一些好看的简单优雅的解决方案。 Is here anyone who can help me ?这里有人可以帮助我吗?

Big thanks十分感谢

Avoiding explicit imports避免显式导入

You can't avoid that, at least not without breaking code completion on IDEs.您无法避免这种情况,至少在不破坏 IDE 上的代码完成的情况下无法避免。

import importlib
import os

filedir = os.path.dirname(__file__)
modules = [f[:-3] for f in os.listdir(filedir) if os.path.isfile(os.path.join(filedir, f)) and f.endswith('.py') and f != '__init__.py']
for module_name in modules:
    module = importlib.import_module(f".{module_name}", package=__name__)
    names = [x for x in module.__dict__ if not x.startswith("_")]
    globals().update({name: getattr(module, name) for name in names})

I wouldn't consider that good looking, simple or elegant.我不会认为它好看,简单或优雅。

Self-replacing generated imports自替换生成的导入

If what's bothering you is having to do it by hand, then probably the best thing you could do is write a script to generate the import statements and replace itself when run.如果困扰您的是必须手动完成,那么您能做的最好的事情可能是编写一个脚本来生成导入语句并在运行时替换自身。

import os

filedir = os.path.dirname(__file__)
modules = [f[:-3] for f in os.listdir(filedir) if os.path.isfile(os.path.join(filedir, f)) and f.endswith('.py') and f != '__init__.py']
imports = [f"    from .{module} import *\n" for module in sorted(modules)]

with open(__file__, 'r') as f:
    this_script = list(f)[:17]

with open(__file__, 'w') as f:
    f.write(f"""{''.join(this_script)[:-1]}
try:
{''.join(imports)[:-1] if imports else '    pass'}
except ImportError:
    pass
""")

try:
    from .oneOfManyFiles import *
except ImportError:
    pass

For code completion, either run the project or python -m api.view.__init__ .要完成代码,请运行项目或python -m api.view.__init__

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM