1
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())
Roman A. Taycher
  • 18,619
  • 19
  • 86
  • 141
  • 2
    It's worse because you don't have any error detection from language or IDE. Also if you forgot # user will see actual code. Moreover if you accidentally call 'I' on string that contains input from user, you will have big security hole. There are probably more reasons. – Tomasz Wysocki Aug 17 '11 at 05:41
  • Maybe an ide or a checker but I think python just craps out with an exception either way,no? – Roman A. Taycher Aug 17 '11 at 05:56
  • 1
    If you have syntax error like "foo)(" Python will raise exception on module-loading time. – Tomasz Wysocki Aug 17 '11 at 13:32

2 Answers2

2

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.

agf
  • 171,228
  • 44
  • 289
  • 238
  • I'm trying to do ruby style string interpolation – Roman A. Taycher Aug 17 '11 at 05:21
  • You can even do crazy stuff like I("#{[x*2 for x in [1,2,3]]}") without multiple lines. But mostly used for stuff like I(" (#{self.name}) has #{self.number_of_children}") – Roman A. Taycher Aug 17 '11 at 05:24
  • A simple syntax for putting variables/expressions in strings – Roman A. Taycher Aug 17 '11 at 05:24
  • 1
    Edited to show that stuff. I don't see how Python's syntax is any more complicated. – agf Aug 17 '11 at 05:28
  • Being positional it makes it somewhat easier to mess up if you have several parameters, also you are taking it away from where the value is in the text. (even if its only a half line). – Roman A. Taycher Aug 17 '11 at 05:33
  • I would actually prefer self.name + " has " + str(self.number_of_children) to the format version – Roman A. Taycher Aug 17 '11 at 05:34
  • 1
    You can use named replacements if you want more clarity... `'{name} has {num_children}'.format(name=self.name, num_children=self.num_children)` which looks even more clear than the ruby version to me. Also, what's wrong with `self.name + ' has ', str(self.num_children)` if you want to keep it simple? Edit: You just commented you prefer this :) – agf Aug 17 '11 at 05:37
  • concatenating: It gets long and a little ugly especially when you have 2-3 non str variables that you need to add spaces around words and periods/newlines : self.name + " has " + str(self.number_of_children) + "." – Roman A. Taycher Aug 17 '11 at 05:42
1

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

Community
  • 1
  • 1
HarmonicaMuse
  • 7,633
  • 37
  • 52