Roman A. Taycher
Roman A. Taycher

Reputation: 19505

What is wrong with this implementation of String interpolation in python*

import re

r = re.compile("#{([^}]*)}")

def I(string):
    def eval_str_match(m):
        return str(eval(m.group(1)))
    return r.sub(eval_str_match,string)

* besides python taste/style/standards

Is there a nicer succinct way to call it then a single letter method?
Is there anything the regex could miss?
should I use repr instead of str ?
I know that eval can be dangerous but I can't see why

I("#{some_func()}\n")

is worse then

"%s\n" % str(some_func())

Upvotes: 1

Views: 375

Answers (2)

HarmonicaMuse
HarmonicaMuse

Reputation: 7893

This is what I came up with.

in my_print.py:

import sys

def mprint(string='', dictionary=None):
    if dictionary is None:            
        caller = sys._getframe(1)
        dictionary = caller.f_locals
    print string.format(**dictionary)

example:

>>> from my_print import mprint
>>> name = 'Ismael'
>>> mprint('Hi! My name is {name}.')
Hi! My name is Ismael.
>>> new_dict = dict(country='Mars', name='Marvin',
...                 job='space monkey', likes='aliens')
>>> mprint("Hi! My name is {name} and I'm from {country}."
...     " Isn't {name} the best name?!\nDo you know any other {name}?", new_dict)
Hi! My name is Marvin and I'm from Mars. Isn't Marvin the best name?!
Do you know any other Marvin?

See:

Python string interpolation implementation

Upvotes: 1

agf
agf

Reputation: 176930

Not sure exactly what you're trying to accomplish, but does this work?

I = '{}\n'.format
I(some_func())

or

def I(func):
    return "%x\n" % func()
I(some_func())

Using your example from the comment,

I([x*2 for x in [1,2,3]])

works fine (though I don't know what it is you want the output to look like), as does

I(''.join((self.name, ' has ', self.number_of_children)))

but you should really just be doing

'{} has {}'.format(self.name, self.number_of_children)

which is still one line.

Upvotes: 2

Related Questions