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 7722941
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T04:19:14+00:00 2026-06-01T04:19:14+00:00

I have a class that overloads object attribute access by returning the attributes of

  • 0

I have a class that overloads object attribute access by returning the attributes of its “row” attribute, along the following lines:

from collections import namedtuple
class MyObj(object):
    def __init__(self, y, z):
        r = namedtuple('row', 'a b')
        self.row = r(y, z)
        self.arbitrary = True
    def __getattr__(self, attr):
        return getattr(self.row, attr)
    def __dir__(self):
        return list(self.row._fields)

In [2]: m = MyObj(1, 2)
In [3]: dir(m)
Out[3]: ['a', 'b']
In [4]: m.a
Out[4]: 1
In [5]: vars(m)
Out[5]: {'arbitrary': True, 'row': row(a=1, b=2)}
In [6]: output = '{a} -> {b}'
In [7]: output.format(**vars(m.row))
Out[7]: '1 -> 2'
In [8]: output.format(**vars(m))
KeyError: 'a'

As I quite often do string formatting using vars() I’d like to be able to access row’s attributes directly from the call to vars(). Is this possible?


Edit following aaronsterling’s answer

The key to solving this, thanks to Aaron’s pointer, is to check for __dict__ in __getattribute__

from collections import namedtuple
class MyObj(object):
    def __init__(self, y, z):
        r = namedtuple('row', 'a b')
        self.row = r(y, z)
        self.arbitrary = True
    def __getattr__(self, attr):
        return getattr(self.row, attr)
    def __getattribute__(self, attribute):
        if attribute == '__dict__':
            return self.row._as_dict()
        else:
            return object.__getattribute__(self, attribute)
    def __dir__(self):
        return list(self.row._fields)

In [75]: m = MyObj(3, 4)

In [76]: m.a
Out[76]: 3

In [77]: vars(m)
Out[77]: OrderedDict([('a', 3), ('b', 4)])
  • 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-06-01T04:19:15+00:00Added an answer on June 1, 2026 at 4:19 am

    The docs are so kind as to specify that vars works by returning the __dict__ attribute of the object it’s called on. Hence overriding __getattribute__ does the trick. Y

    I subclass dict (but see later) to override the __str__ function. The subclass accepts a function str_func which gets called to return a string representation of how you want your __dict__ object to appear. It does this by constructing a regular dictionary with the entries that you want and then calling str on that.

    This is very hacky. In particular, it will break any code that depends on doing anything like

    myobj.__dict__[foo] = bar
    

    This code will now update a phantom dictionary and not the real one.

    A much more robust solution would depend on completely replacing all methods that set values on the SpoofedDict with methods that actually update myobj.__dict__. This would require SpoofedDict instances to hold a reference to myobj.__dict__. Then of course, the methods that read values would have to fetch them out of myobj.__dict__ as well.

    At that point, you’re better off using collections.Mapping to construct a custom class rather than subclassing from dict.

    Here’s the proof of concept code, hackish as it may be:

    from collections import namedtuple
    
    
    class SpoofDict(dict):
        def __init__(self, *args, **kwargs):
            self.str_func = kwargs['str_func']
            del kwargs['str_func']
    
            dict.__init__(self, *args, **kwargs)
    
        def __str__(self):
            return self.str_func()
    
    
    class MyObj(object):
        def __init__(self, y, z):
            r = namedtuple('row', 'a b')
            self.row = r(y, z)
            self.arbitrary = True
        def __getattr__(self, attr):
            return getattr(self.row, attr)
    
        def __dir__(self):
            return list(self.row._fields)
    
        def str_func(self):
            attrs = list(self.row._fields)
            str_dict = {}
            row = object.__getattribute__(self, 'row')
            for attr in attrs:
                str_dict[attr] = getattr(row, attr)
            return str(str_dict)
    
        def __getattribute__(self, attribute):
            if attribute == '__dict__':
                spoof_dict = SpoofDict(str_func=self.str_func)
                spoof_dict.update(object.__getattribute__(self, '__dict__'))
                return spoof_dict                
            else:
                return object.__getattribute__(self, attribute)
    
    
    if __name__=='__main__':
        m = MyObj(1, 2)
        print "dir(m) = {0}".format(dir(m))
        print "vars(m) = {0}".format(vars(m))
        print "m.row = {0}".format(m.row)
        print "m.arbitrary = {0}".format(m.arbitrary)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a class that is marked with DataContract attributes and I would like
I have a class that is created from an enum that can be tested
I have two objects that are derived from same the base class. Lets say
I have an abstract functor class that overloads operator() and derived objects that implement
I have a class called Global that derives from HttpApplication . Oddly, I see
I have a pointer to a QScriptEngine that I'm passing through the overloaded class
I have class that represents users. Users are divided into two groups with different
I have class A such that: class A { static int i; A(); f1();
I have a class that implements the IDisposable interface. I am using a webclient
I have a class that requires a specific method to be called before being

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.