当在sys.modules
中设置项时,一些令人惊讶的值可以用作键:
$ python
>>> import sys
>>> sys.modules["27"] = 123
>>> sys.modules["27"]
123
>>> sys.modules[True] = 123
>>> sys.modules[(1, 7)] = 123
事实上,type
将sys.modules
标识为标准字典.我觉得很令人惊讶。
Python2
>>> type(sys.modules)
<type 'dict'>
Python3 (类型/类统一后)
>>> type(sys.modules)
<class 'dict'>
然而,这些“模块”现在完全无法使用普通的import
机制访问。
在Python标准库中是否有一个函数可以用来识别"good“模块名称/点分离模块”path“,我想使用import
语法来找出哪些东西是重要的,并且通常遵循该语言的惯例。理想情况下,我希望它是标准库的一部分(如果存在的话),以便跟踪Python本身的更改。
发布于 2018-08-31 16:25:12
从技术上讲,要使sys.modules
中的某些内容“重要”,所需的只是一个字符串,据我所知
>>> sys.modules['where is your god now?'] = 42
>>> __import__('where is your god now?')
42
这一限制是由__import__
内置的:
>>> __import__(42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __import__() argument 1 must be str, not int
甚至是unicode!
>>> sys.modules['☃'] = 'looking like christmas?'
>>> __import__('☃')
'looking like christmas?'
尽管要使用import
语句,需要有一个东西作为标识符:
>>> sys.modules['josé'] = ':wave:'
>>> import josé
>>> josé
':wave:'
在python3中,您可以使用字符串上的isidentifier
方法检查某些东西是否是标识符(对于python2,它遵循[a-zA-Z_][a-zA-Z0-9_]*
(我相信)):
>>> 'foo'.isidentifier()
True
>>> 'josé'.isidentifier()
True
>>> '☃'.isidentifier()
False
>>> 'hello world'.isidentifier()
False
如果您想处理虚名:
def dotted_name_is_identifier(x):
return all(s and s.isidentifier() for s in x.split('.'))
用法:
>>> dotted_name_is_identifier('foo.bar')
True
>>> dotted_name_is_identifier('hello.josé')
True
>>> dotted_name_is_identifier('hello. world')
False
>>> dotted_name_is_identifier('hello..world')
False
>>> dotted_name_is_identifier('hello.world.')
False
https://stackoverflow.com/questions/52123886
复制相似问题