V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
leverestfish
V2EX  ›  Python

[提问]如何在一个包内一次性加载模块

  •  
  •   leverestfish · 2021-04-20 20:45:57 +08:00 · 1422 次点击
    这是一个创建于 1073 天前的主题,其中的信息可能已经有所发展或是发生改变。

    小白提问,不知道怎么搜索,求轻喷。 比如经常要用 sys,os,re 等模块,包内的每个文件基本都需要 import 他们,有没有能够一劳永逸地 import 的方法?

    我目前想到的是,在 __init__.py 中加载,然后包中每个模块开头都 from mypackage import * 来实现?这样有什么危害吗?

    感觉自己一直对 import 还有命名空间这一套东西比较迷惑,有比较好的解答文章也恳请赐教一个链接之类的~

    3 条回复    2021-04-21 01:14:45 +08:00
    ClericPy
        1
    ClericPy  
       2021-04-20 21:48:16 +08:00   ❤️ 1
    显式优于隐式... 尽量不要用 *, 有 IDE 自动补全和自动导入, 要啥一劳永逸. 至于每个文件都要导入他们, 可以学一点设计模式方面的知识, 同类 utils 放在一起

    至于命名空间或者其他入门文章, 看看 Real Python 吧, 上面从入门到熟练应有尽有, 如果更喜欢信息量大的, 可以看看 Cookbook 或者 Fluent Python

    Namespaces and Scope in Python – Real Python - https://realpython.com/python-namespaces-scope/
    lakechan96
        2
    lakechan96  
       2021-04-21 00:20:19 +08:00   ❤️ 1
    https://docs.python.org/3/library/site.html

    `This module is automatically imported during initialization.`
    IgniteWhite
        3
    IgniteWhite  
       2021-04-21 01:14:45 +08:00   ❤️ 1
    import * 据说是 PEP8 不推荐的用法
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1154 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 23:03 · PVG 07:03 · LAX 16:03 · JFK 19:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.