Simulate C macro in Python

440 views Asked by At

How can I automagically resolve format specifiers in Python? For example instead of:

MagicPrint(str.format('This is {}', my.name))

I want to write MagicPrint() function as follows:

MagicPrint('This is {my.name}')

Suggestions? Maybe I can use decorators for MagicPrint() function? Please note that my.name is not present in **locals() because MagicPrint() can be called from another module.

3

There are 3 answers

0
Alex Gill On

Used this solution to access caller's variables. Then I have automagical access to print the string.

def MagicPrint(s, *args, **kwargs):
    ''' In order for this to work we need the caller's module variables '''
    f = sys._getframe(1) 
    try:
        print (s.format(*args, **f.f_globals))
    except:
        print (s.format(*args, **f.f_locals))
    else:
        pass
2
kindall On
class my: name = "Jerry"
"This is {my.name}".format(**locals())
0
Ca Pham Van On

that only work on **locals() contains . I am looking for a method that receives a.class_name from another module.

class a: class_name = "name_class"
"This is {a.class_name}".format(**locals())