Python Forum
What would be a way to check if a variable or class existed in an if? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: What would be a way to check if a variable or class existed in an if? (/thread-7119.html)



What would be a way to check if a variable or class existed in an if? - Klar - Dec-21-2017

Something like:
if !x:
    print("Hey!")
or
class x:
    name = 'x'

if !name:
   print("Hi!")
for an alternative for detecting a class.


RE: What would be a way to check if a variable or class existed in an if? - Mekire - Dec-21-2017

You could try and catch NameError.  You shouldn't as this is almost definitely the wrong way to do whatever it is you are trying to do; but you could.


RE: What would be a way to check if a variable or class existed in an if? - SRG - Dec-21-2017

Here you go. The try/catch option is presented as Mekire suggested as is an alternative:
https://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists


RE: What would be a way to check if a variable or class existed in an if? - Mekire - Dec-21-2017

Again however, I would like to point out, especially as you are a beginner, that none of these options are probably what you currently need.  If you share your code we could better instruct you how to refactor it.  It is very rare to need to check membership in any of those dicts or catch name errors.  Checking for class attributes is slightly more common, but again doubtful this is what you need.


RE: What would be a way to check if a variable or class existed in an if? - metulburr - Dec-21-2017

im not sure what you are doing...but you can use builtin isinstance to check

>>> class Klass:
...     pass
... 
>>> obj = Klass()
>>> obj2 = 'str'
>>> isinstance(obj, Klass)
True
>>> isinstance(obj2, Klass)
False
>>> isinstance(obj2, str)
True
>>> isinstance(obj, str)
False



RE: What would be a way to check if a variable or class existed in an if? - Klar - Dec-21-2017

How would I check if a variable exists?


RE: What would be a way to check if a variable or class existed in an if? - wavic - Dec-22-2017

In [1]: my_var = 'I am here!'

In [2]: dir()
Out[2]: 
['In',
 'Out',
 '_',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_dh',
 '_i',
 '_i1',
 '_i2',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 'exit',
 'get_ipython',
 'my_var',
 'quit']

In [3]: if 'my_var' in dir():
   ...:     print("aha")
   ...:     
aha



RE: What would be a way to check if a variable or class existed in an if? - Larz60+ - Dec-22-2017

You can do it with inspect:
class MyTestClass:
    def __init__(self):
        self.list1 = [ ]
        self.fptr = self.method_a
        self.mamals = {
            'rat': {'has_tail': True},
            'dog': {'has_tail': True},
            'guppy': {'has_tail': False, 'has_fin': True}
        }
        self.fptr()

    def method_a(self):
        pass

def try_me():
    import inspect
    from pprint import pprint

    mtc = MyTestClass()

    # Get everything
    for name, member in inspect.getmembers(mtc):
        if name.startswith('__'):
            continue
        pprint(f'name: {name}, member: {member}')

if __name__ == "__main__":
    try_me()
output:
Output:
('name: fptr, member: <bound method MyTestClass.method_a of '  '<__main__.MyTestClass object at 0x00000000028CBE10>>') 'name: list1, member: []' ("name: mamals, member: {'rat': {'has_tail': True}, 'dog': {'has_tail': True}, "  "'guppy': {'has_tail': False, 'has_fin': True}}") ('name: method_a, member: <bound method MyTestClass.method_a of '  '<__main__.MyTestClass object at 0x00000000028CBE10>>')



RE: What would be a way to check if a variable or class existed in an if? - nilamo - Dec-28-2017

(Dec-21-2017, 10:56 PM)Klar Wrote: How would I check if a variable exists?

You should never need to.

PHP has a function called isset(), which you can use to see if a variable exists: http://php.net/manual/en/function.isset.php
Python doesn't have an easy way to do that, because it's not something you should ever need.  If you think you need it, you're probably doing something very wrong.

Please, for the love of *religious figure*, share some code, so that we can help lead you away from this cliff of failure, and onto spiritual enlightenment.