Getting attributes of a class

Question:

I want to get the attributes of a class, say:

class MyClass():
  a = "12"
  b = "34"

  def myfunc(self):
    return self.a

using MyClass.__dict__ gives me a list of attributes and functions, and even functions like __module__ and __doc__. While MyClass().__dict__ gives me an empty dict unless I explicitly set an attribute value of that instance.

I just want the attributes, in the example above those would be: a and b

Asked By: Mohamed Khamis

||

Answers:

MyClass().__class__.__dict__

However, the “right” was to do this is via the inspect module.

Answered By: Borealid

Try the inspect module. getmembers and the various tests should be helpful.

EDIT:

For example,

class MyClass(object):
    a = '12'
    b = '34'
    def myfunc(self):
        return self.a

>>> import inspect
>>> inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
[('__class__', type),
 ('__dict__',
  <dictproxy {'__dict__': <attribute '__dict__' of 'MyClass' objects>,
   '__doc__': None,
   '__module__': '__main__',
   '__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
   'a': '34',
   'b': '12',
   'myfunc': <function __main__.myfunc>}>),
 ('__doc__', None),
 ('__module__', '__main__'),
 ('__weakref__', <attribute '__weakref__' of 'MyClass' objects>),
 ('a', '34'),
 ('b', '12')]

Now, the special methods and attributes get on my nerves- those can be dealt with in a number of ways, the easiest of which is just to filter based on name.

>>> attributes = inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
>>> [a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]
[('a', '34'), ('b', '12')]

…and the more complicated of which can include special attribute name checks or even metaclasses 😉

Answered By: Matt Luongo

myfunc is an attribute of MyClass. That’s how it’s found when you run:

myinstance = MyClass()
myinstance.myfunc()

It looks for an attribute on myinstance named myfunc, doesn’t find one, sees that myinstance is an instance of MyClass and looks it up there.

So the complete list of attributes for MyClass is:

>>> dir(MyClass)
['__doc__', '__module__', 'a', 'b', 'myfunc']

(Note that I’m using dir just as a quick and easy way to list the members of the class: it should only be used in an exploratory fashion, not in production code)

If you only want particular attributes, you’ll need to filter this list using some criteria, because __doc__, __module__, and myfunc aren’t special in any way, they’re attributes in exactly the same way that a and b are.

I’ve never used the inspect module referred to by Matt and Borealid, but from a brief link it looks like it has tests to help you do this, but you’ll need to write your own predicate function, since it seems what you want is roughly the attributes that don’t pass the isroutine test and don’t start and end with two underscores.

Also note: by using class MyClass(): in Python 2.7 you’re using the wildly out of date old-style classes. Unless you’re doing so deliberately for compatibility with extremely old libraries, you should be instead defining your class as class MyClass(object):. In Python 3 there are no “old-style” classes, and this behaviour is the default. However, using newstyle classes will get you a lot more automatically defined attributes:

>>> class MyClass(object):
        a = "12"
        b = "34"
        def myfunc(self):
            return self.a
>>> dir(MyClass)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b', 'myfunc']
Answered By: Ben
def props(cls):   
  return [i for i in cls.__dict__.keys() if i[:1] != '_']

properties = props(MyClass)
Answered By: Doug

I know this was three years ago, but for those who are to come by this question in the future, for me:

class_name.attribute 

works just fine.

Answered By: Jim Jam

My solution to get all attributes (not methods) of a class (if the class has a properly written docstring that has the attributes clearly spelled out):

def get_class_attrs(cls):
    return re.findall(r'w+(?=[,)])', cls.__dict__['__doc__'])

This piece cls.__dict__['__doc__'] extracts the docstring of the class.

Answered By: Henry On

I recently needed to figure out something similar to this question, so I wanted to post some background info that might be helpful to others facing the same in future.

Here’s how it works in Python (from https://docs.python.org/3.5/reference/datamodel.html#the-standard-type-hierarchy):

MyClass is a class object, MyClass() is an instance of the class object. An instance’s __dict__ only hold attributes and methods specific to that instance (e.g. self.somethings). If an attribute or method is part of a class, it is in the class’s __dict__. When you do MyClass().__dict__, an instance of MyClass is created with no attributes or methods besides the class attributes, thus the empty __dict__

So if you say print(MyClass().b), Python first checks the new instance’s dict MyClass().__dict__['b'] and fails to find b. It then checks the class MyClass.__dict__['b'] and finds b.

That’s why you need the inspect module, to emulate that same search process.

Answered By: Scott Howard
import re

class MyClass:
    a = "12"
    b = "34"

    def myfunc(self):
        return self.a

attributes = [a for a, v in MyClass.__dict__.items()
              if not re.match('<function.*?>', str(v))
              and not (a.startswith('__') and a.endswith('__'))]

For an instance of MyClass, such as

mc = MyClass()

use type(mc) in place of MyClass in the list comprehension. However, if one dynamically adds an attribute to mc, such as mc.c = "42", the attribute won’t show up when using type(mc) in this strategy. It only gives the attributes of the original class.

To get the complete dictionary for a class instance, you would need to COMBINE the dictionaries of type(mc).__dict__ and mc.__dict__.

mc = MyClass()
mc.c = "42"

# Python 3.5
combined_dict = {**type(mc).__dict__, **mc.__dict__}

# Or Python < 3.5
def dict_union(d1, d2):
    z = d1.copy()
    z.update(d2)
    return z

combined_dict = dict_union(type(mc).__dict__, mc.__dict__)

attributes = [a for a, v in combined_dict.items()
              if not re.match('<function.*?>', str(v))
              and not (a.startswith('__') and a.endswith('__'))]
Answered By: JD Graham

Getting only the instance attributes is easy.
But getting also the class attributes without the functions is a bit more tricky.

Instance attributes only

If you only have to list instance attributes just use
for attribute, value in my_instance.__dict__.items()

>>> from __future__ import (absolute_import, division, print_function)
>>> class MyClass(object):
...   def __init__(self):
...     self.a = 2
...     self.b = 3
...   def print_instance_attributes(self):
...     for attribute, value in self.__dict__.items():
...       print(attribute, '=', value)
...
>>> my_instance = MyClass()
>>> my_instance.print_instance_attributes()
a = 2
b = 3
>>> for attribute, value in my_instance.__dict__.items():
...   print(attribute, '=', value)
...
a = 2
b = 3

Instance and class attributes

To get also the class attributes without the functions, the trick is to use callable().

But static methods are not always callable!

Therefore, instead of using callable(value) use
callable(getattr(MyClass, attribute))

Example

from __future__ import (absolute_import, division, print_function)

class MyClass(object):
   a = "12"
   b = "34"               # class attributes

   def __init__(self, c, d):
     self.c = c
     self.d = d           # instance attributes

   @staticmethod
   def mystatic():        # static method
       return MyClass.b

   def myfunc(self):      # non-static method
     return self.a

   def print_instance_attributes(self):
     print('[instance attributes]')
     for attribute, value in self.__dict__.items():
        print(attribute, '=', value)

   def print_class_attributes(self):
     print('[class attributes]')
     for attribute in MyClass.__dict__.keys():
       if attribute[:2] != '__':
         value = getattr(MyClass, attribute)
         if not callable(value):
           print(attribute, '=', value)

v = MyClass(4,2)
v.print_class_attributes()
v.print_instance_attributes()

Note: print_class_attributes() should be @staticmethod
      but not in this stupid and simple example.

Result for

$ python2 ./print_attributes.py
[class attributes]
a = 12
b = 34
[instance attributes]
c = 4
d = 2

Same result for

$ python3 ./print_attributes.py
[class attributes]
b = 34
a = 12
[instance attributes]
c = 4
d = 2
Answered By: oHo

If you want to “get” an attribute, there is a very simple answer, which should be obvious: getattr

class MyClass(object):
a = '12'
b = '34'
def myfunc(self):
    return self.a

>>> getattr(MyClass, 'a')
'12'

>>> getattr(MyClass, 'myfunc')
<function MyClass.myfunc at 0x10de45378>

It works dandy both in Python 2.7 and Python 3.x.

If you want a list of these items, you will still need to use inspect.

Answered By: fralau

You can use dir() in a list comprehension to get the attribute names:

names = [p for p in dir(myobj) if not p.startswith('_')]

Use getattr() to get the attributes themselves:

attrs = [getattr(myobj, p) for p in dir(myobj) if not p.startswith('_')]
Answered By: Rotareti

I don’t know if something similar has been made by now or not, but I made a nice attribute search function using vars(). vars() creates a dictionary of the attributes of a class you pass through it.

class Player():
    def __init__(self):
        self.name = 'Bob'
        self.age = 36
        self.gender = 'Male'

s = vars(Player())
#From this point if you want to print all the attributes, just do print(s)

#If the class has a lot of attributes and you want to be able to pick 1 to see
#run this function
def play():
    ask = input("What Attribute?>: ")
    for key, value in s.items():
        if key == ask:
            print("self.{} = {}".format(key, value))
            break
    else:
        print("Couldn't find an attribute for self.{}".format(ask))

I’m developing a pretty massive Text Adventure in Python, my Player class so far has over 100 attributes. I use this to search for specific attributes I need to see.

Answered By: Corey Bailey

This can be done without inspect, I guess.

Take the following class:

 class Test:
   a = 1
   b = 2

   def __init__(self):
     self.c = 42

   @staticmethod
   def toto():
     return "toto"

   def test(self):
     return "test"

Looking at the members along with their types:

t = Test()
l = [ (x, eval('type(x.%s).__name__' % x)) for x in dir(a) ]

… gives:

[('__doc__', 'NoneType'),
 ('__init__', 'instancemethod'),
 ('__module__', 'str'),
 ('a', 'int'),
 ('b', 'int'),
 ('c', 'int'),
 ('test', 'instancemethod'),
 ('toto', 'function')]

So to output only the variables, you just have to filter the results by type, and names not starting with ‘__’. E.g.

filter(lambda x: x[1] not in ['instancemethod', 'function'] and not x[0].startswith('__'), l)

[('a', 'int'), ('b', 'int'), ('c', 'int')] # actual result

That’s it.

Note: if you’re using Python 3, convert the iterators to lists.

If you want a more robust way to do it, use inspect.

Answered By: Carmellose

two function:

def get_class_attr(Cls) -> []:
    import re
    return [a for a, v in Cls.__dict__.items()
              if not re.match('<function.*?>', str(v))
              and not (a.startswith('__') and a.endswith('__'))]

def get_class_attr_val(cls):
    attr = get_class_attr(type(cls))
    attr_dict = {}
    for a in attr:
        attr_dict[a] = getattr(cls, a)
    return attr_dict

use:

>>> class MyClass:
    a = "12"
    b = "34"
    def myfunc(self):
        return self.a

>>> m = MyClass()
>>> get_class_attr_val(m)
{'a': '12', 'b': '34'}
Answered By: redscarf

You can use MyClass.__attrs__. It just gives all the attributes of that class. Nothing more.

Answered By: jimxliu

Python 2 & 3, whitout imports, filtering objects by their address

Solutions in short:

Return dict {attribute_name: attribute_value}, objects filtered. i.e {'a': 1, 'b': (2, 2), 'c': [3, 3]}

{k: val for k, val in self.__dict__.items() if not str(hex(id(val))) in str(val)}

Return list [attribute_names], objects filtered. i.e ['a', 'b', 'c', 'd']

[k for k, val in self.__dict__.items() if not str(hex(id(val))) in str(val)]

Return list [attribute_values], objects filtered. i.e [1, (2, 2), [3, 3], {4: 4}]

[val for k, val in self.__dict__.items() if not str(hex(id(val))) in str(val)]

Not filtering objects

Removing the if condition. Return {'a': 1, 'c': [3, 3], 'b': (2, 2), 'e': <function <lambda> at 0x7fc8a870fd70>, 'd': {4: 4}, 'f': <object object at 0x7fc8abe130e0>}

{k: val for k, val in self.__dict__.items()}

Solution in long

As long as the default implementation of __repr__ is not overridden the if statement will return True if the hexadecimal representation of the location in memory of val is in the __repr__ return string.

Regarding the default implementation of __repr__ you could find useful this answer. In short:

def __repr__(self):
    return '<{0}.{1} object at {2}>'.format(
      self.__module__, type(self).__name__, hex(id(self)))

Wich returns a string like:

<__main__.Bar object at 0x7f3373be5998>

The location in memory of each element is got via the id() method.

Python Docs says about id():

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object in
memory.


Try by yourself

class Bar:

    def __init__(self):

        self.a = 1
        self.b = (2, 2)
        self.c = [3, 3]
        self.d = {4: 4}
        self.e = lambda: "5"
        self.f = object()

    #__str__ or __repr__ as you prefer
    def __str__(self):
        return "{}".format(

            # Solution in Short Number 1
            {k: val for k, val in self.__dict__.items() if not str(hex(id(val))) in str(val)}

        )

# Main
print(Bar())

Output:

{'a': 1, 'c': [3, 3], 'b': (2, 2), 'd': {4: 4}}

Note:

  • Tested with Python 2.7.13 and Python 3.5.3

  • In Python 2.x .iteritems() is preferred over .items()

Answered By: Marco D.G.

Why do you need to list the attributes? Seems that semantically your class is a collection. In this cases I recommend to use enum:

import enum

class myClass(enum.Enum):
     a = "12"
     b = "34"

List your attributes? Nothing easier than this:

for attr in myClass:
    print("Name / Value:", attr.name, attr.value)
Answered By: VengaVenga

The following is what I want.

Test Data

class Base:
    b = 'b'


class MyClass(Base):
    a = '12'

    def __init__(self, name):
        self.name = name

    @classmethod
    def c(cls):
        ...

    @property
    def p(self):
        return self.a

    def my_fun(self):
        return self.name
print([name for name, val in inspect.getmembers(MyClass) if not name.startswith('_') and not callable(val)])  # need `import inspect`
print([_ for _ in dir(MyClass) if not _.startswith('_') and not callable(getattr(MyClass, _))])
# both are equ: ['a', 'b', 'p']

my_instance = MyClass('c')
print([_ for _ in dir(my_instance) if not _.startswith('_') and not callable(getattr(my_instance, _))])
# ['a', 'b', 'name', 'p']
Answered By: Carson

Quick function to get attribute that aren’t magic properties and its value.

The usage of this utility recipe is just to get a quick introspection of a Class or Object without going deep in code or Documentations.
When I used it I just wanted to know that stuff that class has and devide what is a function and what is not, obviously I don’t remember why thought I needed.

For the example, I used Python Faker but anything can be used really.

from faker import Faker
fake = Faker()

def get_class_props(cls):
    for p in dir(cls):
        if not p.startswith('__'):
            attr_value = getattr(cls, p)
            if p.startswith('_'):
                 print(f'- {p} (private): {attr_value}')
            else:
                print(f'- {p}: {attr_value}')

get_class_props(fake)

- _factories (private): [<faker.generator.Generator object at 0x00000138D01D28C8>]
# - _factory_map (private): OrderedDict([('en_US', <faker.generator.Generator object at 0x00000138D01D28C8>)])
# - _locales (private): ['en_US']
# - _map_provider_method (private): <bound method Faker._map_provider_method of <faker.proxy.Faker object at 0x00000138D017AD88>>
# - _select_factory (private): <bound method Faker._select_factory of <faker.proxy.Faker object at 0x00000138D017AD88>>
# - _unique_proxy (private): <faker.proxy.UniqueProxy object at 0x00000138D017A308>
# - _weights (private): None
# - aba: <bound method Provider.aba of <faker.providers.bank.en_GB.Provider object at 0x00000138D281DBC8>>
# - add_provider: <bound method Generator.add_provider of <faker.generator.Generator object at 0x00000138D01D28C8>>
# - address: <bound method Provider.address of <faker.providers.address.en_US.Provider object at 0x00000138D2810DC8>>
# ...

To clean up the funcitions definitions,use this variations instead, wich defines ‘function’ whatever is a callable

from faker import Faker
fake = Faker()

def get_class_props(cls):
    for p in dir(cls):

        if not p.startswith('__'):
            attr_value = getattr(cls, p)
            is_function = callable(attr_value)

            if p.startswith('_'):
                 print(f'- {p} (private): {attr_value if not is_function else "funciton"}')
            else:
                print(f'- {p}: {attr_value if not is_function else "funciton"}')


- _factories (private): [<faker.generator.Generator object at 0x0000018A11D49C48>]
- _factory_map (private): OrderedDict([('en_US', <faker.generator.Generator object at 0x0000018A11D49C48>)])
- _locales (private): ['en_US']
- _map_provider_method (private): funciton
- _select_factory (private): funciton
- _unique_proxy (private): <faker.proxy.UniqueProxy object at 0x0000018A11D49748>
- _weights (private): None
- aba: funciton
get_class_props(fake)
Answered By: Federico Baù

To add filtering features to the answers above :

import inspect
import re

def getClassMembers(obj, name=None, mbrcat='all'):
    # name : filter by attribute name
    # mbrcat : filter members by items category : all, methods or attributes
    dic_cat= { 
        'all' : lambda a: a, 
        'meth' : lambda a: inspect.isroutine(a), 
        'attr' : lambda a:  not(inspect.isroutine(a)) 
      } 
    return [str(_name)+'  :  '+str(member)  
            for _name, member in inspect.getmembers(obj, dic_cat[mbrcat])  
            if ((name==None) or (name in _name)) and (not(re.search(r'(^__|__$)' ,_name))) ]

Call #1:

getClassMembers(myClass.browse(264917),'state')

#Output:
['_compute_activity_state  :  <bound method xxx._compute_activity_state of classXXX >'
 'extract_state  :  no_extract_requested',
 'invoice_payment_state  :  paid',
 'state  :  posted'
] 

Call #2:

getClassMembers(myClass.browse(264917),'state','meth')

#Output:
['_compute_activity_state  :  <bound method xxx._compute_activity_state of classXXX >'
] 

Call #3:

getClassMembers(myClass.browse(264917),'state','attr')
#Ouput:
[
 'extract_state  :  no_extract_requested',
 'invoice_payment_state  :  paid',
 'state  :  posted'
] 
Answered By: sylvain