Python 3软件包和脚本中导入的最佳实践 [英] Best practises for imports in Python 3 packages and scripts

查看:50
本文介绍了Python 3软件包和脚本中导入的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下简单的文件夹结构:

Consider this simple folder structure:

root
  Package1
    x.py
    y.py
  Package2
    z.py
  Examples
    main.py

现在我们的要求是:

  • x.py需要导入y.py
  • z.py需要导入y.py
  • main.py需要导入y.py和z.py

下面是有效的方法:

x.py

import y

def x():
  y()

y.py

def y():
  pass

z.py

import package1.y as y

def z():
  y.y()

main.py

import sys
from os import path
sys.path.append(  path.dirname(  path.dirname( path.abspath(__file__) ) ) )

import package1.y as y
import package2.z as z

y.y()
z.z()

问题:

  1. 这是在Python 3中设置导入的最佳和推荐方法吗?
  2. 我真的不喜欢在main中更改sys.path,因为它强烈绑定了关于程序包位置 inside 代码文件的假设.有什么办法解决吗?
  3. 我也真的不喜欢import package1.y as y中多余的as y部分.有什么办法解决吗?
  1. Is this the best and recommended way to setup imports in Python 3?
  2. I really don't like changing sys.path in main because it strongly binds assumptions about package locations inside code file. Is there any way around that?
  3. I also really don't like superfluous as y part in import package1.y as y. Is there any way around that?

推荐答案

和往常一样,有两个单独的步骤:

As always, there are two separate steps:

  1. 您针对包的抽象名称空间编写代码,该名称空间包含package1package2(以及sysos等.) ,但不是不是包的示例"(因为main.py不是模块).
  2. 您可以在运行任何代码之前 适当地设置sys.path.如果是您自己的代码(未安装),则有您可以放置​​的地方,或者您可以编写简单的Shell脚本包装器为python流程设置 PYTHONPATH .
  1. You write the code against the abstract namespace of packages, which contains package1 and package2 (and sys, os, etc.), but not "Examples" which is not a package (because main.py is not a module).
  2. You set sys.path appropriately before any of your code ever runs. If it's your own (uninstalled) code, there are places you can put it, or you can write an easy shell script wrapper to set PYTHONPATH for your python process.

所以您的问题的答案是

  1. x.py中,您编写from . import y. (Python 2支持此功能,而Python 3支持此功能.)
  2. 如何设置sys.path取决于包装/环境系统.传统方式是为python进程设置PYTHONPATH环境变量,但是还有其他方式涉及诸如site模块之类的东西.
  3. from package1 import y是通常只给事物命名一次的方法.
  1. In x.py you write from . import y. (Python 2 supports this and 3 requires it.)
  2. How you set sys.path depends on your packaging/environment system. The traditional way is to set the PYTHONPATH environment variable for the python process, but there are other ways involving things like the site module.
  3. from package1 import y is the usual way to name things only once.

这篇关于Python 3软件包和脚本中导入的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆