Is there a way to list the attributes of a class without instantiating an object?


In Python 3.5, say I have:

class Foo:
    def __init__(self, bar, barbar): = bar
        self.barbar = barbar

I want to get the list ["bar", "barbar"] from the class.

I know I can do:

foo = Foo(1, 2)

Is there a way to get ["bar", "barbar"] without instantiating an object?

Asked By: vwrobel



No because the attributes are dynamic (so called instance attributes). Consider the following,

class Foo:
    def __init__( self ): = 1

    def twice( self ):
        self.barbar = 2

f = Foo()
print( list(f.__dict__.keys() ) )
print( list(f.__dict__.keys() ) )

In the first print, only was set, so that’s the only attributes that’s shown when printing the attribute keys. But after calling f.twice(), you create a new attribute to f and now printing it show both bar and barbar.

Answered By: Lærne

The following isn’t foolproof in always providing 100% correct data. If you end up having something like self.y = int(1) in your __init__, you will end up including the int in your collection of attributes, which is not a wanted result for your goals. Furthermore, if you happen to add a dynamic attribute somewhere in your code like Foo.some_attr = 'pork', then you will never see that either. Be aware of what it is that you are inspecting at what point of your code, and understand why you have and don’t have those inclusions in your result. There are probably other “breakages” that will not give you the full 100% expectation of what are all the attributes associated with this class, but nonetheless, the following should give you something that you might be looking for.

However, I strongly suggest you take the advice of the other answers here and the duplicate that was flagged that explains why you can’t/should not do this.

The following is a form of solution you can try to mess around with:

I will expand on the inspect answer.

However, I do question (and probably would advice against) the validity of doing something like this in production-ready code. For investigative purposes, sure, knock yourself out.

By using the inspect module as indicated already in one of the other answers, you can use the getmembers method which you can then iterate through the attributes and inspect the appropriate data you wish to investigate.

For example, you are questioning the dynamic attributes in the __init__

Therefore, we can take this example to illustrate:

from inspect import getmembers

class Foo:
    def __init__(self, x):
        self.x = x
        self.y = 1
        self.z = 'chicken'

members = getmembers(Foo)

for member in members:
    if '__init__' in member:

Your output will be a tuple:

('x', 'y', 'z')

Ultimately, as you inspect the class Foo to get its members, there are attributes you can further investigate as you iterate each member. Each member has attributes to further inspect, and so on. For this particular example, we focus on __init__ and inspect the __code__ (per documentation: The __code__ object representing the compiled function body) attribute which has an attribute called co_names which provides a tuple of members as indicated above with the output of running the code.

Answered By: idjaw

As Lærne mentioned, attributes declared inside of functions (like __init__), are dynamic. They effectively don’t exist until the __init__ function is called.

However, there is a way to do what you want.

You can create class attributes, like so:

class Foo:
    bar = None
    barbar = None

    def __init__(self, bar, barbar): = bar
        self.barbar = barbar

And you can access those attributes like this:

[var for var in vars(Foo).keys() if not var.startswith('__')]

Which gives this result:

['bar', 'barbar']
Answered By: Remolten

Try classname.annotations.keys()

Answered By: vinodhraj
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.