user3467349
user3467349

Reputation: 3191

How to check if module attribute is a Class

I am using imp.find_module and then imp.load_module to load 'example', now I want to make a list of just the functions in example.py that are functions of Class A but I can't seem to find a getattr attribute that is unique to Classes which would filter out all other methods in dir(example).

for i in dir(example):
    if hasattr(getattr(example, i), <some_attribute>):
        print i

Upvotes: 3

Views: 2142

Answers (1)

toriningen
toriningen

Reputation: 7462

If you search for existing solution, use builtin inspect module, it has plenty of functions to test for specific types, isclass for your case:

import inspect

class Foo(object):
    pass

if inspect.isclass(Foo):
   print("Yep, it's class")

However, if you want to get into depths, there are few other approaches.

  1. In Python everything is an instance of something. Classes are not an exclusion, they are instances of metaclasses. In Python 2 there are two kinds of classes — old-style (class Foo: pass) and new-style (class Foo(object): pass). Old-style classes are instances of classobj, visible as types.ClassType, while new-style classes are instances of type, which itself is both function and metaclass at the same time (callable metaclass to be strict). In Python 3, there are only new-style classes, always derived from object (which in turn is instance of type).

    So, you can check if Foo is class, by issuing if it's an instance of metaclass producing classes:

    class Foo(object):
        pass
    
    if isinstance(Foo, type):
        print("Yep, it's new-style class")
    

    Or for old-style:

    import types
    
    class Foo:
        pass
    
    if isinstance(Foo, types.ClassType):
        print("Yep, it's old-style class")
    
  2. You can also take a look at data model and list of class-specific magic fields.

Upvotes: 5

Related Questions