在 Python 3 中,是否有内置实用程序来检查两个或多个脚本之间的命名空间重叠?如果没有,我该怎么做?
为了清楚起见更新:我正在寻找一个函数,该函数将返回有关脚本名称空间的信息(即列出脚本中显式定义的所有变量名称、函数名称、类名称等)。
考虑以下场景,
#script 1.py
a = 'spam'
def makeOmlette():
print('eggs and spam')
return None
#script 2.py
a = 'bacon'
def makeOmlette():
print('eggs and bacon')
#Desired Capability:
>>> import someBuiltInModule
>>> someBuiltInModule.BuiltInNameSpaceChecker.compare( scrips = ['folder//script1.py', 'folder//script2.py'])#which would return...
('Scripts are not compatable',
'global variable "a defined in files script1.py and script2.py',
'function "makeOmlette" defined in files cript1.py and script2.py',
'other useful information before you might combine the two...')
目标是检查将脚本 1 和 2 复制并粘贴到同一文件中是否会导致命名空间重叠。
是的,我知道,我可以让新脚本使用 import 语句。
#script 3 - onlyWayIKnow.py
import script_1
import script_2
>>> script_1.a == script_2.a
False
我询问的原因(以防我认为这个问题是错误的)是,如果我使用上述解决方案,我将不得不维护 3 个脚本,而不是 1 个。
Update for clarity: I'm looking for a function that will return information about the namespace of a script (i.e. list all the variable names, function names, class names etc. that are explicitly defined in the script).
Consider the following scenario,
#script 1.py
a = 'spam'
def makeOmlette():
print('eggs and spam')
return None
#script 2.py
a = 'bacon'
def makeOmlette():
print('eggs and bacon')
#Desired Capability:
>>> import someBuiltInModule
>>> someBuiltInModule.BuiltInNameSpaceChecker.compare( scrips = ['folder//script1.py', 'folder//script2.py'])#which would return...
('Scripts are not compatable',
'global variable "a defined in files script1.py and script2.py',
'function "makeOmlette" defined in files cript1.py and script2.py',
'other useful information before you might combine the two...')
The goal would be to check if copying and pasting script 1 and 2 into the same file would cause any namespace overlap.
Yes, I know, I could just have the new script use import statements.
#script 3 - onlyWayIKnow.py
import script_1
import script_2
>>> script_1.a == script_2.a
False
The reason for my inquiry (in case I am thinking about this wrong) is that if I use the aforementioned solution, I would then have to maintain 3 scripts going forward instead of just 1.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不会发生命名空间冲突,因为您导入的是模块,而不是它们的名称。
或者,您可以准确导入您需要的内容,仅此而已,并且可以在必要时重命名它。
另一方面,如果你做了这样的事情,你就会遇到问题,这将是你的错:
You can't have a namespace collision because you imported the modules, not their names.
Alternatively, you can import exactly what you need, nothing more, and you can rename it when necessary.
On the other hand, if you did something like this, you'd have a problem, and it would be your fault: