Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - check for class existance

Is there a way to check if a class has been defined/exists? I have different options on a menu, and some of them require inherited variables, so if you try to select that function before you have set the variables, it crashes. My class is called Gen0, and I started it by simply putting

class Gen0():

Followed by the rest of the code to set the variables. For context, I am doing a population model, so the initial values need to be set (option 1) before displaying (option 2), using (option 3) or exporting (option 4) them.

like image 744
Ollie Avatar asked Jul 03 '16 15:07

Ollie


1 Answers

Your situation is not entirely clear, so I'm just going to answer the question "Is there a way to check if a class has been defined/exists?"

Yes, there are ways to check if a class has been defined in the current scope. I'll go through a few.

1. It's Better to Ask Forgiveness Than Permission

Just try to use it!

try:
    var = MyClass()
except NameError:
    # name 'MyClass' is not defined
    ...

This is probably the most Pythonic method (aside from just being sure you have the class imported/defined).

2. Look Through Current Scope

Everything in the current scope is given by dir(). Of course, this won't handle things that are imported! (Unless they are imported directly.)

if not 'MyClass' in dir():
    # your class is not defined in the current scope
    ...

3. Inspect a Module's Contents

Perhaps you want to see if the class is defined within a specific module, my_module. So:

import my_module
import inspect

if not 'MyClass' in inspect.getmembers(my_module):
    # 'MyClass' does not exist in 'my_module'
    ...

Now, it's worth pointing out that if at any point you are using these sorts of things in production code, you're probably writing your code poorly. You should always know which classes are in scope at any given point. After all, that's why we have import statements and definitions. I'd recommend you clean up your question with more example code to receive better responses.

like image 135
Pierce Darragh Avatar answered Oct 04 '22 21:10

Pierce Darragh