推荐学习书目
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 · Apr 20, 2021 · 2323 views
    This topic created in 1848 days ago, the information mentioned may be changed or developed.

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

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

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

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

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

    Namespaces and Scope in Python – Real Python - https://realpython.com/python-namespaces-scope/
    lakechan96
        2
    lakechan96  
       Apr 21, 2021   ❤️ 1
    https://docs.python.org/3/library/site.html

    `This module is automatically imported during initialization.`
    FurN1
        3
    FurN1  
       Apr 21, 2021   ❤️ 1
    import * 据说是 PEP8 不推荐的用法
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1596 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 16:38 · PVG 00:38 · LAX 09:38 · JFK 12:38
    ♥ Do have faith in what you're doing.