Python string interpolation implementation

牧云@^-^@ 提交于 2019-11-28 11:23:46
Ashwini Chaudhary

Modules don't share namespaces in python, so globals() for my_print is always going to be the globals() of my_print.py file ; i.e the location where the function was actually defined.

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

You should pass the current module's globals() explicitly to make it work.

Ans don't use mutable objects as default values in python functions, it can result in unexpected results. Use None as default value instead.

A simple example for understanding scopes in modules:

file : my_print.py

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

file : 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
Burhan Khalid

Part of your problem - well, the reason its not working - is highlighted in this question.

You can have your function work by passing in globals() as your second argument, mprint('Hello my name is {name}',globals()).

Although it may be convenient in Ruby, I would encourage you not to write Ruby in Python if you want to make the most out of the language.

Ismael VC

Language Design Is Not Just Solving Puzzles: ;)

http://www.artima.com/forums/flat.jsp?forum=106&thread=147358

Edit: PEP-0498 solves this issue!

The Template class from the string module, also does what I need (but more similar to the string format method), in the end it also has the readability I seek, it also has the recommended explicitness, it's in the Standard Library and it can also be easily customized and extended.

http://docs.python.org/2/library/string.html?highlight=template#string.Template

from string import Template

name = 'Renata'
place = 'hospital'
job = 'Dr.'
how = 'glad'
header = '\nTo Ms. {name}:'

letter = Template("""
Hello Ms. $name.

I'm glad to inform, you've been
accepted in our $place, and $job Red
will ${how}ly recieve you tomorrow morning.
""")

print header.format(**vars())
print letter.substitute(vars())

The funny thing is that now I'm getting more fond of using {} instead of $ and I still like the string_interpolation module I came up with, because it's less typing than either one in the long run. LOL!

Run the code here:

http://labs.codecademy.com/BE3n/3#:workspace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!