Albert
Albert

Reputation: 68110

NameError for globals

In some Python modules, I have code like this:

try:
    someGlobal
except NameError:
    someGlobal = []

This can be important in case I want to support module reloading and some certain object must not be overwritten (e.g. because I know that it is referred to directly).

Many editors (e.g. PyCharm) mark this as an error. Is there some other way to write the same code which is more Python idiomatic? Or is this already Python idiomatic and it's a fault of the editors to complain about this?

Upvotes: 0

Views: 70

Answers (2)

Alex Martelli
Alex Martelli

Reputation: 881567

I'd go with

if 'someGlobal' not in dir():
    someGlobal = 23

This has the advantage of simplicity, but can be a bit slow if the module has a lot of globals, since dir() is a list and the in operator on it is O(N).

For speed, and at a modest disadvantage in terms of simplicity,

if 'someGlobal' not in vars():
    someGlobal = 23

which should be faster since vars() is a dict, so the in operator on it is O(1).

Upvotes: 4

Scott Hunter
Scott Hunter

Reputation: 49803

It is an error, at least given the information availale to the editor. So the editor isn't wrong; it is just that you are specifically coding for that error.

Upvotes: 0

Related Questions