Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert one list to set, but if empty use a default one

Tags:

python

list

set

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)
like image 952
Deleted Avatar asked Feb 21 '12 12:02

Deleted


3 Answers

only = set(args.onlyTheseServers or availableServers)
like image 200
Chris Morgan Avatar answered Oct 10 '22 01:10

Chris Morgan


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.

like image 24
jcollado Avatar answered Oct 10 '22 01:10

jcollado


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']
like image 24
Rik Poggi Avatar answered Oct 10 '22 02:10

Rik Poggi