简体   繁体   中英

Is using “try” to see if a variable is defined considered bad practice in Python?

I have the following piece of code inside a function:

try:
    PLACES.append(self.name)
except NameError:
    global PLACES
    PLACES = [self.name]

Which causes from <file containing that code> import * to return

SyntaxWarning: name 'PLACES' is used prior to global declaration
  global PLACES

So I was wondering if it is considered bad practice to do such a thing, and if so, what is the correct way of doing it? I'm a noob btw.

Yes, it is considered a bad practice. Just make sure the variable is defined. Virtually always, this is as simple as as module-level assignment with a reasonable default value:

Places = []

When the default value should not be instantiated at import time (eg if it is very costy, or has some side effect), you can at least initialize None and check whether the_thing is None when it's needed, initializing it if it's still None .

The first problem is you shouldn't do from foo import * , this is just bad practice and will cause namespace collisions (without any warnings, by the way), and will cause you headaches later on.

If you need to share a global storage space between two modules; consider pickling the object and unpickling it where required; or ak/v store, cache or other external store. If you need to store rich data, a database might be ideal.

Checking if a name points to a object is usually a sign of bad design somewhere. You also shouldn't assume to pollute the global namespace if a name doesn't exist - how do you know PLACES wasn't deleted intentionally?

I only suggest you move global PLACES out of except block:

global PLACES
try:
    PLACES.append(self.name)
except NameError:
    PLACES = [self.name]

Just define:

PLACES = []

before anything else.

Than later:

PLACE.append(self.name)

If checked with

if PLACES:

an empty list yields false. This way you can tell if there are any places there already. Of course, you don't need to check anymore before you append.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM