I'm looking for a nicer way to assign a set with the conent of a list if such list is not empty, otherwise another list should be used.
If it is possible I'd like a nicer way to write this (or an argument to why this is the nicest way):
if args.onlyTheseServers:
only = set(args.onlyTheseServers)
else:
only = set(availableServers)
only = set(args.onlyTheseServers or availableServers)
Looking at your previous question, I'd say that what you're really looking for is a way to assign a default value to a missing parameter using argparse
. In that case you should just use default
as follows:
parser.add_argument('-o', '--only', default=default_servers, ...)
This way, when the -o/--only
option isn't passed, the namespace will have the default value correctly set.
args.onlyTheseServers
seems a variable coming from argparse
.
If that's your case you should check the default
argument and the set_default()
method.
Here's 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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With