Python string interpolation implementation

后端 未结 3 801
盖世英雄少女心
盖世英雄少女心 2020-12-10 16:53

[EDIT 00]: I\'ve edited several times the post and now even the title, please read below.

I just learned about the format string method, and its use with dictionarie

相关标签:
3条回答
  • 2020-12-10 17:16

    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
    
    0 讨论(0)
  • 2020-12-10 17:36

    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.

    0 讨论(0)
  • 2020-12-10 17:37

    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

    0 讨论(0)
提交回复
热议问题