Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

namespace scope for variables inside try block

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?

like image 737
ealeon Avatar asked Jul 16 '26 00:07

ealeon


2 Answers

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
like image 104
MSeifert Avatar answered Jul 18 '26 14:07

MSeifert


You can use locals() to see the defined variables in each case. There is no difference.

like image 41
LeopoldVonBuschLight Avatar answered Jul 18 '26 14:07

LeopoldVonBuschLight



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!