0

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.

1

3 Answers 3

0
class my: name = "Jerry"
"This is {my.name}".format(**locals())
Sign up to request clarification or add additional context in comments.

2 Comments

That will only work when **locals() contains the my.name variable. I am looking for a method that receives my.name from another module.
You might want to put that in your question. You could also use vars(modulename) to get the variables from that module.
0

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())

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.