gpt4 book ai didi

Python字符串插值实现

转载 作者:太空狗 更新时间:2023-10-29 21:55:24 24 4
gpt4 key购买 nike

[EDIT 00]:我已经多次编辑帖子,现在甚至编辑标题,请阅读下文。

我刚刚了解了格式字符串方法及其与字典的用法,例如 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()< 中值的字典范围。

我已经尝试使用非本地和点符号来访问主模块变量,但我仍然无法弄明白。


[编辑 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)

在测试.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.

小伙伴们怎么看?这对我来说很难!

我喜欢它,对我来说更具可读性。


[编辑 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

然后在这里克隆 grom git repo: https://github.com/Ismael-VC/python_string_interpolation.git

最佳答案

模块在 python 中不共享命名空间,因此 my_printglobals() 始终是 my_print 的 globals() .py 文件;即函数实际定义的位置。

def mprint(string='', dic = None):
dictionary = dic if dic is not None else globals()
print string.format(**dictionary)

您应该显式传递当前模块的 globals() 以使其工作。

Ans 不要在 python 函数中使用可变对象作为默认值,它会导致 unexpected results .使用 None 作为默认值。

一个理解模块范围的简单例子:

文件:my_print.py

x = 10
def func():
global x
x += 1
print x

文件:main.py

from my_print import *
x = 50
func() #prints 11 because for func() global scope is still
#the global scope of my_print file
print x #prints 50

关于Python字符串插值实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16504732/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com