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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T10:13:30+00:00 2026-06-01T10:13:30+00:00

I am trying to find a way to set dict values encapsulated into a

  • 0

I am trying to find a way to set dict values encapsulated into a class, for example using __getattr__ i can return the internal dict value, however the __setattr__ is called even when attributes exists, making my implementation ugly. The example below is simplified my actual class inherits from a Subject class (the subject part of the observer pattern)

i am trying to achieve something like this:

obj = Example()
obj.username = 'spidername' # all OK username is a key in the internal dict
# but company is not a key in the internal dict so
obj.company = 'ABC' # will raise AttributeError

and i am asking if there is a better way than the way i am doing below:

class Example(object):
    def __init__(self, table=None):
        self._fields = {}
        self._table = table

    def _set_fields(self):
        """
        this method will be implemented by 
        subclasses and used to set fields names and values
        i.e.
        self._field['username'] = Field(default='unknown', is_primary=False)
        """
        raise NotImplementedError

    def __getattr__(self, name):
        """
        great this method is only called when "name"
        is not an attribute of this class
        """
        if name in self._fields:
            return self._fields[name].value
        return None

    def __setattr__(self, name, value):
        """
        not so great, this method is called even for
        attributes that exists in this class

        is there a better way to do the following?             
        this can be in __init__, but its still ugly
        """
        attribs = ['_fields', '_table'] 
        if name in attribs:
            super(Example, self).__setattr__(name, value)
        else:
            if name in self._fields:
                self._fields[name].value = value
            else:
                raise AttributeError

EDIT: adjusted comment in code, added missin quotes

  • 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-01T10:13:32+00:00Added an answer on June 1, 2026 at 10:13 am

    The problem is that the attributes don’t exist when they are first assigned. In __init__, when you first assign a dict to _fields, _fields is not an attribute. It only becomes an existing attribute after its been assigned. You could use __slots__ if you know in advance what the attributes are, but my guess is that you don’t. So my suggestion would be to insert these into the instance dict manually:

    class Example(object):
        def __init__(self, table=None):
            self.__dict__['_fields'] = {}
            self.__dict__['_table'] = table
    
        ...
    
        def __setattr__(self, name, value):
            if name in self._fields:
                self._fields[name].value = value
            else:
                raise AttributeError
    

    However, with this implementation, the only way you can add or change instance attributes later would be through __dict__. But I assume this is not likely.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to find a way in which I can return a generic set,
So I'm trying to find a way to return a very large result set
I am trying to find a way, using AFNetworking, to set the Content-Type header
I have been trying to find a way to set variables for one class
I'm trying to find a way to easily generate an example/demonstration data set from
I'm trying to find a tidy way to set a string using an if
I'm trying to find a way to set a cookie that sets a user's
I am trying to find out a way to set a time tag to
Hi I'm trying to find out if there is a way to set the
I am trying to find a way to query rows of data by using

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.