Python中的裸词/新关键字 [英] Bare words / new keywords in Python
问题描述
我想看看是否可以定义新的关键字,或者如 WAT的销毁所有软件"讲座中所定义的那样在Ruby中讨论Ruby的裸露语言时.
I wanted to see if it was possible to define new keywords or, as they're called in WAT's Destroy All Software talk when discussing Ruby, bare words, in Python.
我想出了一个我在其他地方找不到的答案,所以我决定在StackOverflow上分享它的Q& A风格.
I came up with an answer that I couldn't find elsewhere, so I decided to share it Q&A style on StackOverflow.
推荐答案
到目前为止,我仅在REPL中任何块之外尝试了此操作.也有可能使其在其他地方工作.
I've only tried this in the REPL, outside any block, so far. It may be possible to make it work elsewhere, too.
我将其放在我的python启动文件中:
I put this in my python startup file:
def bareWordHandler(type_, value, traceback_):
if isinstance(value, SyntaxError):
import traceback
# You can probably modify this next line so that it'll work within blocks, as well as outside them:
bareWords = traceback.format_exception(type_, value, traceback_)[1].split()
# At this point we have the raw string that was entered.
# Use whatever logic you want on it to decide what to do.
if bareWords[0] == 'Awesome':
print(' '.join(bareWords[1:]).upper() + '!')
return
bareWordsHandler.originalExceptHookFunction(type_, value, traceback_)
import sys
bareWordsHandler.originalExceptHookFunction = sys.excepthook
sys.excepthook = bareWordsHandler
快速REPL会话演示后记:
Quick REPL session demonstration afterwords:
>>> Awesome bare words
BARE WORDS!
负责任地使用.
这是一个更有用的示例.我添加了run
关键字.
Here's a more useful example. I added in a run
keyword.
if bareWords[0] == 'from' and bareWords[2] == 'run':
atPrompt.autoRun = ['from ' + bareWords[1] + ' import ' + bareWords[3].split('(')[0],
' '.join(bareWords[3:])]
return
atPrompt.autoRun
是变量的列表,当显示我的提示时,这些变量将被自动检查并反馈.因此,例如,我可以这样做:
atPrompt.autoRun
is a list of variables that, when my prompt is displayed, will automatically be checked and fed back. So, for example, I can do this:
>>> from loadBalanceTester run loadBalancerTest(runJar = False)
这被解释为:
from loadBalancerTest import loadBalancerTest
loadBalancerTest(runJar = False)
这有点像宏-对我来说,做这种事情很常见,因此我决定添加一个关键字,使我可以减少击键次数.
It's kind of like a macro - it's common for me to want to do this kind of thing, so I decided to add in a keyword that lets me do it in fewer keystrokes.
这篇关于Python中的裸词/新关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!