解析python的超集,允许内联模块导入表达式
import-expression的Python项目详细描述
导入表达式分析器(缺少更好的名称)
导入表达式解析器转换如下代码:
x=collections.deque!(maxsize=2)
输入等效代码:
x=importlib.import_module('collections').deque(maxsize=2)
用法
>>>importimport_expression>>>import_expression.eval('collections!.Counter("bccdddeeee")')Counter({'e':4,'d':3,'c':2,'b':1})
默认情况下,SyntaxError
s的文件名是<string>
。
要更改此项,请通过filename
kwarg传入文件名。
ast使用
猴子修补repl
>>>urllib.parse!.quoteFile"<stdin>",line1urllib.parse!.quote^SyntaxError:invalidsyntax>>>importimport_expression.patch>>>import_expression.patch.patch(globals())>>>urllib.parse!.quote<functionquoteat0xdeadbeef>
为了方便起见,您还可以在sitecustomize.py
中添加以下两行:
importimport_expression.patchimport_expression.patch.patch()
所有repl会话都将使用导入表达式语法。
限制/已知问题
- 尚未检测到某些无效语法,如
urllib!.parse!
, 尽管它仍然像urllib.parse!
那样工作。 - 因为该死的是f-string解析,而且由于
!
已经是f-string中的运算符, F字符串中的导入表达式可能永远不受支持。 - 由于python的限制,
import_expression.exec
的结果对调用方的全局变量没有影响 没有明确的globals
参数。
常见问题解答
实际上为一个新项目提出了问题!天哪!
为什么不直接使用
__import__('x')
?
从discord.py server:devon#4089: if i want to type
_("thing")
devon#4089: i have to move my fingers between three different locations
devon#4089: both at the end and start of the string
lambda#0987: yeah and [it's] also a pain to type on mobile so ok
devon#4089: <<x>> is slightly less grating \对于上下文,最初建议的语法是<;<;x>;。
License
版权所有©2018 Benjamin Mintz<;bmintz@protonmail.com>;。保留所有权利。
根据麻省理工学院的许可证。有关详细信息,请参见license.md文件。