Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3404804
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T05:25:40+00:00 2026-05-18T05:25:40+00:00

I need a way to inspect a class so I can safely identify which

  • 0

I need a way to inspect a class so I can safely identify which attributes are user-defined class attributes. The problem is that functions like dir(), inspect.getmembers() and friends return all class attributes including the pre-defined ones like: __class__, __doc__, __dict__, __hash__. This is of course understandable, and one could argue that I could just make a list of named members to ignore, but unfortunately these pre-defined attributes are bound to change with different versions of Python therefore making my project volnerable to changed in the python project – and I don’t like that.

example:

>>> class A:
...   a=10
...   b=20
...   def __init__(self):
...     self.c=30
>>> dir(A)
['__doc__', '__init__', '__module__', 'a', 'b']
>>> get_user_attributes(A)
['a','b']

In the example above I want a safe way to retrieve only the user-defined class attributes [‘a’,’b’] not ‘c’ as it is an instance attribute. So my question is… Can anyone help me with the above fictive function get_user_attributes(cls)?

I have spent some time trying to solve the problem by parsing the class in AST level which would be very easy. But I can’t find a way to convert already parsed objects to an AST node tree. I guess all AST info is discarded once a class has been compiled into bytecode.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T05:25:40+00:00Added an answer on May 18, 2026 at 5:25 am

    Below is the hard way. Here’s the easy way. Don’t know why it didn’t occur to me sooner.

    import inspect
    
    def get_user_attributes(cls):
        boring = dir(type('dummy', (object,), {}))
        return [item
                for item in inspect.getmembers(cls)
                if item[0] not in boring]
    

    Here’s a start

    def get_user_attributes(cls):
        boring = dir(type('dummy', (object,), {}))
        attrs = {}
        bases = reversed(inspect.getmro(cls))   
        for base in bases:
            if hasattr(base, '__dict__'):
                attrs.update(base.__dict__)
            elif hasattr(base, '__slots__'):
                if hasattr(base, base.__slots__[0]): 
                    # We're dealing with a non-string sequence or one char string
                    for item in base.__slots__:
                        attrs[item] = getattr(base, item)
                else: 
                    # We're dealing with a single identifier as a string
                    attrs[base.__slots__] = getattr(base, base.__slots__)
        for key in boring:
            del attrs['key']  # we can be sure it will be present so no need to guard this
        return attrs
    

    This should be fairly robust. Essentially, it works by getting the attributes that are on a default subclass of object to ignore. It then gets the mro of the class that’s passed to it and traverses it in reverse order so that subclass keys can overwrite superclass keys. It returns a dictionary of key-value pairs. If you want a list of key, value tuples like in inspect.getmembers then just return either attrs.items() or list(attrs.items()) in Python 3.

    If you don’t actually want to traverse the mro and just want attributes defined directly on the subclass then it’s easier:

    def get_user_attributes(cls):
        boring = dir(type('dummy', (object,), {}))
        if hasattr(cls, '__dict__'):
            attrs = cls.__dict__.copy()
        elif hasattr(cls, '__slots__'):
            if hasattr(base, base.__slots__[0]): 
                # We're dealing with a non-string sequence or one char string
                for item in base.__slots__:
                    attrs[item] = getattr(base, item)
                else: 
                    # We're dealing with a single identifier as a string
                    attrs[base.__slots__] = getattr(base, base.__slots__)
        for key in boring:
            del attrs['key']  # we can be sure it will be present so no need to guard this
        return attrs
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need a way to bind POJO objects to an external entity, that could
Is there a way to debug a function that is defined dynamically in run
I need a javascript bookmarklet which can click on a button. The thing is,
Need a way to allow sorting except for last item with in a list.
I need a way to easily export and then import data in a MySQL
I need a way to recursively delete a folder and its children. Is there
I need a way to update the month value on a dateTime field in
I need a way to build C++ code from UML diagrams and vice versa.
I need a way to represent a 2-D array (a dense matrix) of doubles
I need a way to allow each letter of a word to rotate through

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.