简体   繁体   English

将字典作为参数传递给python中的函数,其中参数是函数本身

[英]Passing dictionary as argument to a function in python where the arguments are functions themselves

I am currently working with Python3 and the plotnine library.我目前正在使用 Python3 和 plotnine 库。

I am trying to use plotnine with a dictionary as arguments.我正在尝试使用带有字典的 plotnine 作为参数。 Here is a simple working example of what I am trying to do :这是我正在尝试做的一个简单的工作示例:

import pandas as pd
import plotnine as p9

iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')

plot = p9.ggplot(data=iris, mapping=p9.aes(x='petal_width')) +\
 p9.geom_density(fill='#6bd1e8', alpha=0.5) +\
 p9.theme(axis_title_x = p9.element_text(size = 20),\
         axis_text_x = p9.element_text(size=10, angle = 45))

print(plot)

Here, I want to use my dictionary in the 'p9.theme' function, but these function arguments are function themselves ('p9.element_text').在这里,我想在“p9.theme”函数中使用我的字典,但这些函数参数本身就是函数(“p9.element_text”)。

Now I have a simple dictionary :现在我有一个简单的字典:

theme:
  axis_title_x:
    size: 20
  axis_text_x:
    size: 10
    angle: 45

For now it works partially if I do something like :现在,如果我执行以下操作,它会部分起作用:

p9.theme(axis_title_x = p9.element_text(**conf['axis_title_x']),\
         axis_text_x = p9.element_text(**conf['axis_text_x']))

But I would like something like :但我想要类似的东西:

p9.theme(**conf['theme'])

I tried changing the structure of my dictionary but I cannot get it to work.我尝试更改字典的结构,但无法使其正常工作。 Does anyone have an idea on how to do this or a workaround maybe?有没有人知道如何做到这一点或解决方法?

Thanks谢谢

You have too pass function in the dictionary.您在字典中也有传递功能。 Problem is that function **kwargs cannot be referred within same dictionary at the point of creation.问题是函数**kwargs在创建时不能在同一个字典中引用。 So there are two ways.所以有两种方法。 Have two dictionaries:有两本词典:

def test(a, b, c=None):
    print(a, b, c)

def foo(x):
    return f'!{x}'

sub_conf = {
    'foo': {'x': 2}
}

conf = {
    'test': {'a': 1, 'b': foo(**sub_conf['foo'])}
}

test(**conf['test'])

Or create dictionary in steps so you can refer existing object.或者分步创建字典,以便您可以引用现有对象。

conf = {
    'foo': {'c': 2}
}

conf['test'] = {'a': 1, 'b': foo(**conf['foo'])}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM