python 3:日志函数签名问题

python 3:日志函数签名问题,python,function,python-3.x,argument-passing,Python,Function,Python 3.x,Argument Passing,我经常编写以下代码: print('object', 'moved', 'from =', object.location, 'dest =', new_location) print('object', 'created', 'at =', object.location, 'status =', status) 等等 我计划用一个函数log替换所有这些: def log(self, action, **details): print('object', action, end = ''

我经常编写以下代码:

print('object', 'moved', 'from =', object.location, 'dest =', new_location)
print('object', 'created', 'at =', object.location, 'status =', status)
等等

我计划用一个函数
log
替换所有这些:

def log(self, action, **details):
  print('object', action, end = '')
    for var, value in state.items():
      print(var, '=', value, end = '')
    print()
这几乎是可行的——除了两个问题。首先,我不能控制输出的顺序,这对我很重要。当然,
details
只是一个字典,所以参数的顺序丢失了。其次,我不能使用任何语言关键字,例如,
from
作为关键字参数的名称

是否有任何解决方案可以避免不必要的冗长,但不会出现这些问题

我想使用
log
功能的原因是我可能想禁用/启用该功能,或者在单个位置更改格式。

您知道该模块,我接受了吗

我只会使用预先生成的消息,并在以下内容中替换必要的位:

movedmsg = "object moved from = %s to = %s"
print(movedmsg % (object.location, new_location))
您可能更喜欢新样式的字符串格式:

movedmsg = "object moved from = {0} to = {1}"
print(movedmsg.format(object.location, new_location))
如果您确实需要使用类似于词典的结构,您可以制作一个OrderedDict。但这有点冗长。而且这并不是“一种显而易见的方法”。

我想你知道这个模块吧

我只会使用预先生成的消息,并在以下内容中替换必要的位:

movedmsg = "object moved from = %s to = %s"
print(movedmsg % (object.location, new_location))
您可能更喜欢新样式的字符串格式:

movedmsg = "object moved from = {0} to = {1}"
print(movedmsg.format(object.location, new_location))

如果您确实需要使用类似于词典的结构,您可以制作一个OrderedDict。但这有点冗长。而且这并不是真正的“一种显而易见的方法”。

我能想到的最干净的解决方案是传入一组键/值对

def log(action, *details):
    print('object', action, end = '')
    for var, value in details:
        print(var, '=', value, end = '')
    print()

log("moved", ("from", obj.location), ("dest", new_location))
您可以编写一个函数来捕获格式字符串并返回另一个执行实际日志记录的函数。如果您要经常使用单一格式,这可能会很有用

def makelogger(*format):
    def logger(action, *args):
        print("object", action, format % args)
    return logger

logger = makelogger("from = %s dest = %s")
logger("moved", obj.location, new_location)

# do a one-off
makelogger("from = %s dest = %s")("moved", obj.location, new_location)

只是一些想法。

我能想到的最干净的解决方案是传入一组键/值对

def log(action, *details):
    print('object', action, end = '')
    for var, value in details:
        print(var, '=', value, end = '')
    print()

log("moved", ("from", obj.location), ("dest", new_location))
您可以编写一个函数来捕获格式字符串并返回另一个执行实际日志记录的函数。如果您要经常使用单一格式,这可能会很有用

def makelogger(*format):
    def logger(action, *args):
        print("object", action, format % args)
    return logger

logger = makelogger("from = %s dest = %s")
logger("moved", obj.location, new_location)

# do a one-off
makelogger("from = %s dest = %s")("moved", obj.location, new_location)

只是一些想法。

我绝对建议您查看日志模块。Vinay已经写了一个很好的操作指南,希望它能让人更容易理解:我绝对建议您查看日志模块。Vinay已经写了一个很好的操作指南,希望能让它变得更加平易近人: