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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T07:43:52+00:00 2026-05-29T07:43:52+00:00

I’m writing a python class that uses __setattr__ and __getattr__ to provide custom attribute

  • 0

I’m writing a python class that uses __setattr__ and __getattr__ to provide custom attribute access.

However, some attributes can’t be handled in a generic way, so I was hoping to use descriptors for those.

A problem arises in that for a descriptor, the descriptor’s __get__ will be invoked in favour of the instances __getattr__, but when assigning to an attribute, __setattr__ will be invoked in favour of the descriptors __set__.

An example:

class MyDesc(object):

    def __init__(self):
        self.val = None

    def __get__(self, instance, owner):
        print "MyDesc.__get__"
        return self.val

    def __set__(self, instance, value):
        print "MyDesc.__set__"
        self.val = value

class MyObj(object):

    foo = MyDesc()

    def __init__(self, bar):
        object.__setattr__(self, 'names', dict(
            bar=bar,
        ))
        object.__setattr__(self, 'new_names', dict())

    def __setattr__(self, name, value):
        print "MyObj.__setattr__ for %s" % name
        self.new_names[name] = value

    def __getattr__(self, name):
        print "MyObj.__getattr__ for %s" % name

        if name in self.new_names:
            return self.new_names[name]

        if name in self.names:
            return self.names[name]

        raise AttributeError(name)

if __name__ == "__main__":
    o = MyObj('bar-init')

    o.bar = 'baz'
    print o.bar

    o.foo = 'quux'
    print o.foo

prints:

MyObj.__setattr__ for bar
MyObj.__getattr__ for bar
baz
MyObj.__setattr__ for foo
MyDesc.__get__
None

The descriptor’s __set__ is never called.

Since the __setattr__ definition isn’t just overriding behaviour for a limited set of names, there’s no clear place that it can defer to object.__setattr__

Is there a recommended way to have assigning to attributes use the descriptor, if available, and __setattr__ otherwise?

  • 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-29T07:43:54+00:00Added an answer on May 29, 2026 at 7:43 am

    update

    Revisiting this answer more than 10 years later, I realized that I included a recipe, but did not explain the outstanding behavior the OP met: a descritpor’s __get__ is called before an instance’s __getattr__, yes. But the actual converse to __setattr__ is __getattribute__, not __getattr__. Inside object‘s __getattribute__ is where is the code with the search order for attributes in first place, and the code responsible for calling a descriptor’s __get__ itself. __getattr__ is called by the code in __getattribute__ itself as a last resort, after inspecting any possible descriptors, __slots__, and the instance’s __dict__.

    original answer: just do what the OP wants to achieve

    I think I’d approach this by having a mechanism to automatically mark which are the
    descriptors in each class, and wrap the __setattr__ in a way that it’d call
    object’s normal behavior for those names.

    This can be easily achieved with a metaclass (and a decorator for __setattr__

    def setattr_deco(setattr_func):
        def setattr_wrapper(self, attr, value):
            if attr in self._descriptors:
                return object.__setattr__(self, attr, value)
            return setattr_func(self, attr, value)
        return setattr_wrapper
    
    class MiscSetattr(type):
        def __new__(metacls, name, bases, dct):
            descriptors = set()
            for key, obj in dct.items():
                if key == "__setattr__":
                    dct[key] = setattr_deco(obj)
                elif hasattr(obj, "__get__"):
                    descriptors.add(key)
            dct["_descriptors"] = descriptors
            return type.__new__(metacls, name, bases, dct)
        
    # and use MiscSetattr as metaclass for your classes
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I am doing a simple coin flipping experiment for class that involves flipping a
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I need a function that will clean a strings' special characters. I do NOT

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.