Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: loop over classes?

Tags:

python

How can I combine the following into a loop in python?

    try:
        [fb.delete() for fb in FacebookProfile.objects.filter(user_id=user.id)]
    except FacebookProfile.DoesNotExist:
        pass

    try:
        [fb.delete() for fb in FacebookUser.objects.filter(user_id=user.id)]
    except FacebookUser.DoesNotExist:
        pass

    try:
        [fb.delete() for fb in FacebookLike.objects.filter(user_id=user.id)]
    except FacebookLike.DoesNotExist:
        pass

    try:
        [fb.delete() for fb in FacebookInvite.objects.filter(user_id=user.id)]
    except FacebookInvite.DoesNotExist:
        pass

As we can see it's the same code block, just with the class name changing in each one, so I'm looking to iterate over an array of class names and run each through a generated function with the same semantics as above.

like image 411
user1640189 Avatar asked Jan 26 '26 12:01

user1640189


1 Answers

for klass in [FacebookProfile, FacebookUser, FacebookLike, FacebookInvite]:
    try:
        for fb in klass.objects.filter(user_id=user.id):
            fb.delete()
    except klass.DoesNotExist:
        pass
like image 63
phihag Avatar answered Jan 28 '26 01:01

phihag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!