简体   繁体   English

访问Python模块中的别名函数

[英]Access to aliased functions in a Python module

I am consolidating many shell-like operations into a single module. 我正在将许多类似shell的操作整合到一个模块中。 I would then like to be able to do: 然后,我希望能够做到:

pyscript.py:
from shell import *
basename("/path/to/file.ext")

and the shell.py module contains: shell.py模块包含:

shell.py:
from os.path import basename

The problem is that functions imported to the shell module are not available, since the import statement only includes functions, classes, and globals defined in the "shell" module, not ones that are imported. 问题在于,导入到shell模块的函数不可用,因为import语句仅包含在“ shell”模块中定义的函数,类和全局变量,而不包括导入的函数,类和全局变量。

Is there any way to get around this? 有什么办法可以解决这个问题?

Are you sure you're not just using the wrong syntax? 您确定不只是使用了错误的语法吗? This works for me in 2.6. 这在2.6中对我有效。

from shell import * 
basename("/path/to/file.ext")

shell.py: shell.py:

from os.path import basename

It's not a bug, it's a feature :-) 这不是一个错误,这是一个功能 :-)

If you import m1 in a module m2 and then import m2 into another module, it will only import things from m2, not from m1. 如果将m1导入模块m2中,然后将m2导入另一个模块中,则它将仅从m2中导入内容,而不是从m1中导入内容。 This is to prevent namespace pollution. 这是为了防止命名空间污染。

You could do this: 您可以这样做:

shell.py: shell.py:

import os.path
basename = os.path.basename

Then, in pyscript.py, you can do this: 然后,在pyscript.py中,您可以执行以下操作:

from shell import * # warning: bad style!
basename(...)

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

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