samedi 27 juin 2020

Get random string that is not in list

I have a list of choices. Let's assume it's ['active', 'inactive', 'deleted']. I want to get a random string that isn't in that list (for example, disabled) and complication is that I don't want to look into that list myself (function must work universally for any list of string).

I know how to get random string from list with random.choice. What I want is to have inversed equivalent of it.

Actual case - I want to write a unittest with an assertNotIn assertion.

So, my code at the moment is below:

import random
import string

insiders = ['active', 'inactive', 'deleted']

while True:
    outsider = ''.join(random.choice(string.ascii_letters) for _ in range(random.choice(range(1, 10))))
    if outsider not in insiders:
        break

My question is: Is there any shorter solution? Ideally, one-liner. Something like this:

outsider = random.not_in_list(insiders)



Aucun commentaire:

Enregistrer un commentaire