data_garden data_garden - 1 month ago 9
Python Question

Python - None argument

I have a function with 4 arguments:

def uploadDatabase(user,filter1,filter2, name):
"""uploads playlists to database

if a playlist satisfying both filters is not long enough,
we pick a playlist based on one single filter"""

playlist_filter1 = [x['track'] for x in filter1]
playlist_filter2 = [x['track'] for x in filter2]
playlist_both_filters = [x['track'] for x in filter2 if x['track'] in [y['track'] for y in filter1]]

#create an empty dict for user as key
double_filter = {str(user):{}}
single_filter1 = {str(user):{}}
single_filter2 = {str(user):{}}
#set initial playback number for each track
count = 1
#set counts to tracks
double_filter[str(user)] = dict(zip(playlist_both_filters, [count for i in playlist_both_filters]))
db_double = double_filter
#set counts to tracks
single_filter1[str(user)] = dict(zip(playlist_filter1, [count for i in playlist_filter1]))
db_single1 = single_filter1
(...)


however, sometimes
filter2
won't be passed:

uploadDatabase(user,energy_playlist, None, 'my playlist')


how do I fix
uploadDatabase()
and tell it to ignore
None Type
being assigned to variables
playlist_filter2
and
double_filter
, given the fact that both need valid
lists
?

Answer

You can convert the None types to valid empty lists for both filters by doing:

playlist_filter1 = [x['track'] for x in filter1] if filter1 is not None else []
playlist_filter2 = [x['track'] for x in filter2] if filter2 is not None else []

instead of:

playlist_filter1 = [x['track'] for x in filter1]
playlist_filter2 = [x['track'] for x in filter2]