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.
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.
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).
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
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With