我在python中使用ConfigObj进行模板式插值.通过**展开我的配置字典似乎不进行插值.这是一个功能还是一个bug?有什么好的解决方法吗?
$ cat my.conf
foo = /test
bar = $foo/directory
>>> import configobj
>>> config = configobj.ConfigObj('my.conf', interpolation='Template')
>>> config['bar']
'/test/directory'
>>> '{bar}'.format(**config)
'$foo/directory'
Run Code Online (Sandbox Code Playgroud)
我希望第二行是/test/directory.为什么插值不能用**kwargs?
我有一个C++类,我正在使用boost :: python构建一个python模块.我有一些函数,我想采取关键字参数.我已经设置了包装函数来传递给raw_arguments,并且工作正常,但我想构建一些函数参数的错误检查.有没有标准的方法来做到这一点?
我的函数原型,在C++中,看起来有点像这样:
double MyClass::myFunction(int a, int b, int c);
Run Code Online (Sandbox Code Playgroud)
第三个参数是可选的,默认值为0(到目前为止,我已经使用宏在boost :: python中实现了这个).在python中,我希望能够实现以下行为:
MyClass.my_function(1) # Raises exception
MyClass.my_function(2, 3) # So that a = 2, b = 3 and c defaults to 0
MyClass.my_function(2, 3, 1) # As above, but now c = 1
MyClass.my_function(2, 3, 1, 3) # Raises exception
MyClass.my_function(3, 1, c = 2) # So a = 3, b = 1 and c = 2
MyClass.my_function(a = 2, b = 2, c = 3) # Speaks …Run Code Online (Sandbox Code Playgroud) 我知道如果函数接受,我可以将函数参数转换为字典**kwargs.
def bar(**kwargs):
return kwargs
print bar(a=1, b=2)
{'a': 1, 'b': 2}
Run Code Online (Sandbox Code Playgroud)
但是,情况恰恰相反?我可以将命名参数打包到字典中并返回它们吗?手动编码版本如下所示:
def foo(a, b):
return {'a': a, 'b': b}
Run Code Online (Sandbox Code Playgroud)
但似乎必须有更好的方法.请注意,我试图避免**kwargs在函数中使用(命名参数对于代码完成的IDE更有效).
我正在尝试使用Python的type annotations抽象类.我的__init__功能看起来像这样:
from abc import ABCMeta
class SomeClass(object, metaclass=ABCMeta):
def __init__(self, *args, **kwargs):
print("Initiating %s object.", self.__class__.__name__)
self.username = kwargs['data']
assert isinstance(self.username, str)
is_premioum = kwargs.get('premioum', False)
self.money_investmant = kwargs.get('investmant')
if isinstance(self.money_investmant, str):
self.money_investmant = float(self.money_investmant)
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,kwargs可能包含从几个数字类型-的参数float,bool和str.
现在,我正在尝试为函数编写类型注释,如下所示:
def __init__(self, *args, **kwargs: Union[bool, str, float]) -> None:
Run Code Online (Sandbox Code Playgroud)
但我的PyCharmIDE提醒我:
除了'Integral'类型,取而代之的是'str'
和:
在bool中找不到referance'get' str | 浮动'
难道我做错了什么?
如果kwargs包含来自多个类型的参数,我应该如何编写kwargs的类型注释?
我以下工作是例外.
def foo(**kwargs):
print kwargs
foo(**{'a':'b'})
foo(**{u'a':'b'})
Run Code Online (Sandbox Code Playgroud)
回溯(最近一次调用最后一次):TypeError中的文件"",第1行:m()关键字必须是字符串
我做错了什么或者我应该修理它吗?
这件事现在让我误解了一段时间:
def test (*args, **kwargs):
print target
test(foo='bar', target='baz')
Run Code Online (Sandbox Code Playgroud)
我认为target='test'在底部的aFunc调用最终会出现在kwargs中(并且确实如此),并且我还假设**会在函数调用中解包kwargs,因此target将作为aFunc中的关键字参数存在.它没有.我知道它作为一个dict出现,但我需要在参数列表中解压缩该dict.这可能吗?简而言之,有没有办法让*args和**kwargs消失并让实际的args和kwargs进入通话?
编辑:我汇总了一个案例,其中*args和**kwargs的解包可能会有所帮助:
假设我有一个打印列表的函数:
def printList (inputList=None):
print inputList
Run Code Online (Sandbox Code Playgroud)
我希望能够不传递任何列表并提供默认列表:
def ensureList (listFunc):
def wrapper (inputList=None):
listFunc(inputList=inputList or ['a','default','list'])
return wrapper
@ensureList
def printList (inputList=None):
print inputList
Run Code Online (Sandbox Code Playgroud)
现在我想让列表转发器变得更复杂:
@ensureList
def repeatList (inputList=None):
print inputList*2
Run Code Online (Sandbox Code Playgroud)
这很好.但现在我想要变量重复:
@ensureList
def repeatList (times, inputList=None):
print inputList*times
Run Code Online (Sandbox Code Playgroud)
现在你可以说:
repeatList(5)
Run Code Online (Sandbox Code Playgroud)
它会生成默认列表并重复5次.
当然,这会失败,因为包装器无法处理times参数.我当然可以这样做:
@ensureList
def repeatList (inputList=None, times=1)
Run Code Online (Sandbox Code Playgroud)
但后来我总是这样做:
repeatList(times=5)
Run Code Online (Sandbox Code Playgroud)
也许在某些情况下我想强制提供一个值,所以非关键字arg是有意义的.
当我去年第一次遇到这样的问题时,我认为一个简单的解决方案是删除包装器上的要求:
def ensureList (listFunc):
"info here re: operating on/requiring an inputList keyword arg"
def wrapper …Run Code Online (Sandbox Code Playgroud) 我想做这样的事情:
class A(object):
def __init__(self, **kwargs):
"""
return exception if certain arguments not set
"""
class B(A):
def __init__(self, **kwargs):
super(B, self).__init__(**kwargs)
Run Code Online (Sandbox Code Playgroud)
基本上,每个子类都需要正确实例化某些参数.它们是相同的参数.我只想一次检查这些参数.如果我可以从父init()做到这一点- 那就更好了.
是否有可能做到这一点?
我正在使用Python试图找出一个关键词,我看到了单词" kwargs",我知道这是在被调用函数中的某种参数,但我无法找到它在任何地方的含义或代表.
例如,Python文档中的这个条目说......
read_holding_registers(address, count=1, **kwargs)
Run Code Online (Sandbox Code Playgroud)
address – The starting address to read from
count – The number of registers to read
unit – The slave unit this request is targeting
Run Code Online (Sandbox Code Playgroud)
它看起来像是指向指针的引用,但这就是我能说的全部......
这甚至不在**kwargs参数列表中使用" "它使用我看起来像" unit"而不是" kwargs"的东西.
我似乎找不到任何kwargs意味着什么.
也许这是"关键词论证"?我在这里错过了什么?
这里的任何想法都有帮助?谢谢 !短发
我想调整条形图中的错误栏属性.显然,这是通过使用关键字参数(即在error_kw中)来完成的.例如
from pylab import *
fig = figure()
ax = fig.add_subplot(111)
ax.plot( left=0, width=1, height=5, error_kw=dict(elinewidth=3, ecolor='b') )
Run Code Online (Sandbox Code Playgroud)
但是,我找不到可能的error_kw值的列表.
我提前为提出这样一个微不足道的问题而道歉,但我无法在任何地方找到它,这让我感到疯狂.
我想知道为什么我应该使用kwargs或args而不是传递简单的dict(如果是args,则使用元组)?
我写了一个非常简单的代码片段来检查到底发生了什么,而我找不到任何专家在字典上使用kwarg。如果有人能告诉我为什么我应该使用那些,我会很高兴的。现在,正如我所看到的,它只是更多的pythonic,但没有任何区别。同样,如果您使用简单的字典,那么它会更易读,因为所有语言都可以做到这一点,但不能采用kwargs方式。
def test_normal(input: dict):
for element in input.items():
print('Type: {}, raw: {}'.format(type(input), input))
print('key: {}, value: {}'.format(element[0], element[1]))
def test_kwargs(**kwargs):
for element in kwargs.items():
print('Type: {}, raw: {}'.format(type(kwargs), kwargs))
print('key: {}, value: {}'.format(element[0], element[1]))
test_normal(dict(name='Joseph'))
test_kwargs(name='Joseph')
Run Code Online (Sandbox Code Playgroud)
Type: <class 'dict'>, raw: {'name': 'Joseph'}
key: name, value: Joseph
Type: <class 'dict'>, raw: {'name': 'Joseph'}
key: name, value: Joseph
Run Code Online (Sandbox Code Playgroud) kwargs ×10
python ×9
dictionary ×2
arguments ×1
boost-python ×1
c++ ×1
configobj ×1
matplotlib ×1
python-2.7 ×1
python-3.x ×1
type-hinting ×1
typing ×1
unicode ×1