[编辑00]:我已经编辑了好几次帖子,现在甚至是标题,请在下面阅读。Python字符串插值实现
我只是了解了格式字符串的方法,其使用词典使用,就像vars()
,locals()
和globals()
,例如提供者:
name = 'Ismael'
print 'My name is {name}.'.format(**vars())
但我想做的事:
name = 'Ismael'
print 'My name is {name}.' # Similar to ruby
所以我想出了这个:
def mprint(string='', dictionary=globals()):
print string.format(**dictionary)
你可以用这里的代码交互: http://labs.codecademy.com/BA0B/3#:workspace
最后,我很想做的是在另一个文件中的函数,名为my_print.py
,所以我可以做的:
from my_print import mprint
name= 'Ismael'
mprint('Hello! My name is {name}.')
但因为它现在,范围有问题,我怎么能从导入的mprint函数中将主模块名称空间作为字典来获取。 (不是从my_print.py
)
我希望我让自己理解,如果不是,尝试从另一个模块导入功能。 (回溯在链接中)
它从my_print.py
访问globals()
字典,但当然变量名没有在该范围内定义,有关如何完成此任务的任何想法?
该函数如果在同一个模块中定义,但注意我必须如何使用globals()
,因为如果不是,我只会得到一个值在mprint()
范围内的字典。
我已经尝试使用nonlocal和点符号来访问主模块变量,但我仍然无法弄清楚。
[编辑01]:我想我已经找到了一个解决方案:
在my_print.py:
def mprint(string='',dictionary=None):
if dictionary is None:
import sys
caller = sys._getframe(1)
dictionary = caller.f_locals
print string.format(**dictionary)
在test.py:
from my_print import mprint
name = 'Ismael'
country = 'Mexico'
languages = ['English', 'Spanish']
mprint("Hello! My name is {name}, I'm from {country}\n"
"and I can speak {languages[1]} and {languages[0]}.")
它打印:
Hello! My name is Ismael, I'm from Mexico
and I can speak Spanish and English.
你认为什么人?对我来说这是一件困难的事情!
我喜欢它,对我更具可读性。
[EDIT 02]:我已完成的模块与interpolate
功能,Interpolate
类和用于interpolate
类方法类似的方法的功能的尝试。
它有一个小测试套件和它的记录!
我卡在方法的实现,我不明白。
下面的代码:http://pastebin.com/N2WubRSB
你觉得什么人?
[编辑03]:好的我现在只用interpolate()
函数解决了。
在string_interpolation.py
:
import sys
def get_scope(scope):
scope = scope.lower()
caller = sys._getframe(2)
options = ['l', 'local', 'g', 'global']
if scope not in options[:2]:
if scope in options[2:]:
return caller.f_globals
else:
raise ValueError('invalid mode: {0}'.format(scope))
return caller.f_locals
def interpolate(format_string=str(),sequence=None,scope='local',returns=False):
if type(sequence) is str:
scope = sequence
sequence = get_scope(scope)
else:
if not sequence:
sequence = get_scope(scope)
format = 'format_string.format(**sequence)'
if returns is False:
print eval(format)
elif returns is True:
return eval(format)
再次感谢你们!有什么意见?
[编辑04]:
这是我的最后一个版本,它有一个测试,文档字符串并介绍了一些限制,我发现: http://pastebin.com/ssqbbs57
您可以在这里快速测试代码: http://labs.codecademy.com/BBMF#:workspace
和克隆格罗姆混帐回购协议在这里: https://github.com/Ismael-VC/python_string_interpolation.git
相关:?是一个字符串格式化从其呼叫范围的做法不好拉变量(http://stackoverflow.com/questions/13312240/is- a-string-formatter-that-pulls-variables-from-calling-scope-bad-practice) – jfs 2013-05-12 08:10:35
related:[打印变量名称和内容作为调试工具;寻找emacs/Python快捷方式](http://stackoverflow.com/questions/2813227/printing-variable-names-and-contents-as-debugging-tool-looking-for-emacs-python) – jfs 2013-05-12 08:13:29
这是一个有趣的练习,但我会警告这种隐含的行为:Python不鼓励它(“显式比隐式更好”意味着这里'mprint('...',vars())'比'mprint('...')要好回到调用者并获取它的局部变量),我认为它的确有很好的理由(明确的代码可以更容易地阅读和维护)。 – EOL 2013-05-12 13:28:55