3

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?

MSeifert
  • 145,886
  • 38
  • 333
  • 352
ealeon
  • 12,074
  • 24
  • 92
  • 173
  • 3
    **try** is not a new scoping block. The scope of the variable is from first appearance to the end of the function, class, ... – Prune Aug 29 '17 at 18:02
  • 2
    `except: pass` shouldn't be preferred – PRMoureu Aug 29 '17 at 18:03
  • There is an interesting question that someone has marked as a duplicate of this. Should it be closed on this? https://stackoverflow.com/questions/45292479/name-binding-in-except-clause-deleted-after-the-clause – cs95 Aug 29 '17 at 18:11
  • @cᴏʟᴅsᴘᴇᴇᴅ I don't think so. That Q+A is specifically about the catched exception in the except block and only in python-3.x. – MSeifert Aug 29 '17 at 18:16
  • 1
    @cᴏʟᴅsᴘᴇᴇᴅ Nah, nah. There's a slight difference between the questions. The dupe I linked to was asking why declaring a global name, and then using the name in `except as ` was raising a `NameErrror` when the name was later used. There're definitely related, but not exact dupes. – Christian Dean Aug 29 '17 at 18:16

3 Answers3

8

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
MSeifert
  • 145,886
  • 38
  • 333
  • 352
1

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

1

There is no difference in the resulting state after execution of the two statements you gave.

If you omit the userid="" in the second, the variable will result undefined if an error occurs.

The first statement should be preferred since it is (a) nicer and (b) faster (userid gets a value assigned twice if no error occurs).

Leolo
  • 416
  • 1
  • 5
  • 12