简体   繁体   中英

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.

I am trying to use plotnine with a dictionary as arguments. 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').

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. 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'])}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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