Mike
Mike

Reputation: 785

How can I test to see if a defaultdict(set) is empty in Python

I have a defaultdict fishparts = defaultdict(set) that has elements assigned to it but is periodically cleared using .clear() What I need is some way to test if the set is clear or not so I can do some other work in the function below.

def bandpassUniqReset5(player,x,epochtime):
    score = 0
    if lastplay[player] < (epochtime - 300):
        fishparts[player].clear()
    lastplay[player] = epochtime
    for e in x:
        # right here I want to do a check to see if the "if" conditional above has cleared fishparts[player] before I do the part below
        if e not in fishparts[player]:
            score += 1
        fishparts[player].add(e)
    return str(score)

Upvotes: 4

Views: 10459

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124110

Sets, like all Python containers, are considered False when empty:

if not fishparts[player]:
    # this set is empty

See Truth Value Testing.

Demo:

>>> if not set(): print "I am empty"
... 
I am empty
>>> if set([1]): print "I am not empty"
... 
I am not empty

Upvotes: 10

Related Questions