How to set an argument if it exists in the configuration file, and not include it if it does not exist.

Asked 1 years ago, Updated 1 years ago, 388 views

In the case of else, there is a Type Error because you put NoneType where you need to put the dict.

definition(config:dict):
    If A in config:
        A=config ['A']
    else:
        A = None
    create_instance(
        OptionA=A
    )
create_instance(OptionA:dict):
....

What I want to do is to put a dict called config['A'] in option A of create_instance if there is a dict called A in the config, and if there is no dictation, I would like to do the same as putting nothing in the argument.

In the first place, I think it's wrong to put it in at a different point, but I'm worried about how to solve it.

As a provisional measure, I think there will be no problem, but if you do the same with other arguments when the create_instance argument becomes more than one, it will be full of ifs. I would appreciate it if you could let me know if there is any other good way.

 if A in config:
     A=config ['A']
    create_instance(
        OptionA=A
    )
else:
    A = None
    create_instance()

python

2022-11-18 21:19

1 Answers

I think the code mentioned in the question is a little different, but

  • I want to call a function with the keyword argument OptionA when config has key A
  • I want to call a function without a keyword argument when the config does not have a key A

I interpreted it as a question.

kwargs={}
if 'A' in config;
    kwargs ['OptionA'] = config ['A']

Create_instance(**kwargs)#Expand keyword argument from dict and call

I think it would be good if


2022-11-18 21:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.