Regarding these two options:
try:
userid = get_userid()
except:
userid = ""
vs.
userid = ""
try:
userid = get_userid()
except:
pass
Is there any difference, specifically wondering how the namespace would work out if userid is only set within the try block? Do they both have the same namespace scope?
Is one preferred over the other?
Blocks like try and except (but also if, elif, else, with) have no "local scope". However you can't and shouldn't expect that any code in the try block will be executed (because it could fail and go directly in the except or finally block).
But are you sure that "" as "failing" user_id makes sense? Why not something else, for example None?
Also you should avoid catching all exceptions, so I would prefer something like this:
try:
userid = get_userid()
except Exception: # or a more specific exception
userid = None
You can use locals() to see the defined variables in each case. There is no difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With