English 中文(简体)
显示格式的定型
原标题:Capturing **vars() pattern in string formatting

我经常发现自己使用了以下模式来扼制格式。

a = 3
b =  foo 
c = dict(mykey= myval )

#prints a is 3, b is foo, mykey is myval
print( a is {a}, b is {b}, mykey is {c[mykey]} .format(**vars()))

这就是说,我常常需要在当地名称空间印刷价值,以呼呼呼呼var。 然而,在我看一看我的代码时,似乎总是重复<代码>.format(**vars()的模式。

我愿建立一种能够反映这一模式的职能。 情况如下。

# doesn t work
def lfmt(s):
    """
    lfmt (local format) will format the string using variables
    in the caller s local namespace.
    """
    return s.format(**vars())

除非在<代码>上出现Imt名称空间时,斜体已不复存在。

我怎么能写下lf,以便把var(var)放在打电话者的名字空间中,这样,以下法典就能够发挥上述作用?

print(lfmt( a is {a}, b is {b}, mykey is {c[mykey]} ))
最佳回答
问题回答

你们必须检查电话线中的变量。

这将使你开始:

import inspect
import pprint

def lfmt(s):
    for frame in inspect.getouterframes(inspect.currentframe()):
        f = frame[0]
        print pprint.pformat(f.f_locals)
    return  ??? 

if __name__ ==  __main__ :
    a = 10
    b = 20
    c = 30
    lfmt( test )

阁下:

import sys

def lfmt(s):
    """
    lfmt (local format) will format the string using variables
    in the caller s local namespace.
    """

    if hasattr(sys, "tracebacklimit") and sys.tracebacklimit == 0:
        raise Exception, "failfailfail"

    try:
        raise ZeroDivisionError
    except ZeroDivisionError:
        f = sys.exc_info()[2].tb_frame.f_back

    return s.format(**f.f_locals)

a = 5
somestring = "text"
print lfmt("{a} {somestring}")

这样做并不意味着你应该使用。 这就是开发商所称的“主要 ha车”,通常用“第三十号指示”发出评论。

否 每一次,你都称职?

def lfmt(s,v):
    """
    lfmt (local format) will format the string using variables
    from the dict returned by calling v()"""
    return s.format(**v())

print(lfmt( a is {a}, b is {b}, mykey is {c[mykey]} ,vars))




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签