python local modules

余生长醉 提交于 2019-12-12 07:58:28

问题


I have several project directories and want to have libraries/modules that are specific to them. For instance, I might have a directory structure like such:

myproject/
  mymodules/
    __init__.py
    myfunctions.py
  myreports/
    mycode.py

Assuming there is a function called add in myfunctions.py, I can call it from mycode.py with the most naive routine:

execfile('../mymodules/myfunctions.py')
add(1,2)

But to be more sophisticated about it, I can also do

import sys
sys.path.append('../mymodules')
import myfunctions

myfunctions.add(1,2)

Is this the most idiomatic way to do this? There is also some mention about modifying the PYTHONPATH (os.environ['PYTHONPATH']?), but is this or other things I should look into?

Also, I have seen import statements contained within class statements, and in other instances, defined at the top of a Python file which contains the class definition. Is there a right/preferred way to do this?


回答1:


Don't mess around with execfile or sys.path.append unless there is some very good reason for it. Rather, just arrange your code into proper python packages and do your importing as you would any other library.

If your mymodules is in fact a part of one large project, then set your package up like so:

myproject/
    __init__.py
    mymodules/
        __init__.py
        myfunctions.py
    myreports/
        __init__.py
        myreportscode.py

And then you can import mymodules from anywhere in your code like this:

from myproject.mymodules import myfunctions
myfunctions.add(1, 2)

If your mymodules code is used by a number of separate and distinct projects, then just make it into a package in its own right and install it into whatever environment it needs to be used in.



来源:https://stackoverflow.com/questions/7732685/python-local-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!