Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: determine if a class is nested

Suppose you have a python method that gets a type as parameter; is it possible to determine if the given type is a nested class?
E.g. in this example:

def show_type_info(t):
    print t.__name__
    # print outer class name (if any) ...

class SomeClass:
    pass

class OuterClass:
    class InnerClass:
        pass

show_type_info(SomeClass)
show_type_info(OuterClass.InnerClass)

I would like the call to show_type_info(OuterClass.InnerClass) to show also that InnerClass is defined inside OuterClass.

like image 695
Paolo Tedesco Avatar asked Mar 12 '09 15:03

Paolo Tedesco


People also ask

How do you check if an object is of a certain class Python?

Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object. For example, isinstance(x, int) to check if x is an instance of a class int .

Does Python have nested classes?

A class defined in another class is known as an inner class or nested class. If an object is created using child class means inner class then the object can also be used by parent class or root class.

How can we check whether the object is instance of class or not?

The isinstance() function checks if the object (first argument) is an instance or subclass of the class info class (second argument).

How do you check if something is a object in Python?

Python isinstance() Function Python's built-in isinstance(object, class) function takes an object and a class as input arguments. It returns True if the object is an instance of the class. Otherwise, it returns False .


1 Answers

AFAIK, given a class and no other information, you can't tell whether or not it's a nested class. However, see here for how you might use a decorator to determine this.

The problem is that a nested class is simply a normal class that's an attribute of its outer class. Other solutions that you might expect to work probably won't -- inspect.getmro, for example, only gives you base classes, not outer classes.

Also, nested classes are rarely needed. I would strongly reconsider whether that's a good approach in each particular case where you feel tempted to use one.

like image 111
John Feminella Avatar answered Oct 14 '22 07:10

John Feminella