Convert one list to install, but if empty, use the default value

I am looking for a more convenient way to assign a set with a list connector, if such a list is not empty, otherwise a different list should be used.

If possible, I would like it to be better (or an argument why this is the most enjoyable way):

if args.onlyTheseServers: only = set(args.onlyTheseServers) else: only = set(availableServers) 
+6
source share
5 answers
 only = set(args.onlyTheseServers or availableServers) 
+11
source

Looking at the previous question, I would say that what you are really looking for is a way to assign a default value to a missing parameter using argparse . In this case, you should simply use default as follows:

 parser.add_argument('-o', '--only', default=default_servers, ...) 

Thus, when the -o/--only option -o/--only not passed, the namespace will be set correctly by default.

+3
source

args.onlyTheseServers seems to be a variable coming from argparse .

If in this case you should check the default argument and set_default() .

Here is an example:

 >>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo', nargs='*', default=['1', '2', '3']) >>> args = parser.parse_args() >>> args.foo ['1', '2', '3'] >>> args = parser.parse_args(['--foo', 'a', 'b']) >>> args.foo ['a', 'b'] 
+2
source

Not much better, but at least a little shorter:

 only = set(availableServers if args.onlyTheseServers is None else args.onlyTheseServers) 

You can also do

 only = set(args.onlyTheseServers or availableServers) 

It works a little differently, since it does not test None , but only if the argument is true - is there - in this case it should work.

+1
source

Call me crazy buy I like it better

 only = set(args.onlyTheseServers) if args.onlyTheseServers is not None else set(availableServers) 
0
source

Source: https://habr.com/ru/post/908970/


All Articles