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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T22:10:08+00:00 2026-05-31T22:10:08+00:00

I would like to create a class that behaves as a python variable but

  • 0

I would like to create a class that behaves as a python variable but calls some callback function when the “variable” is changed/read.

In other words, I’d like to be able to use the class as follows:

x=myClass(change_callback, read_callback)

defines x as an instance of myclass. The constructor (INIT) takes 2 functions as paramater: a function to be called each time x is changed, and a function to be called each time x is “read”

The following statement:

x=1

would “save” 1 and trigger a call to change_callback(1) which could do anything.

The following statement:

a=x

would retrieve the stored value and call read_callback() which would possibly change the stored value and do other things.

I would like this to work with any type, e.g. to be able to write things like:

x=[1 2 3] which would trigger change_callback([1 2 3])

x.append(4) would trigger change_callback([1 2 3 4]) (and possibly a call to read_callback() before)

x={'a':1} would trigger change_callback({'a':1})

print(x) would trigger a call to read_callback()…and return the last stored value for printing, of course.

The idea is that any access to the variable could be logged, or generate other calculation… seemlessly.

I get the feeling this should be possible, but I don’t really see what my object should inherit from…
If I have to restrict me to one type,e.g. a list, is there any way to redefine all assignment operators (including methods like append()…) in “one go”, keeping the original behaviour (the base class method) and adding the callback…

Or are there more appropriate ways (modules…) to achieve the same goals…?

Thanks in advance,

  • 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-31T22:10:09+00:00Added an answer on May 31, 2026 at 10:10 pm

    Objects don’t know when they get assigned to a variable. Writing x = a adds a dict entry (or locals entry) that points to a. The a object doesn’t get notified (though, in CPython, its reference count gets incremented).

    The part that does get notified is the container where the object is assigned. In the case of a global assignment, the module dictionary gets updated. In the case of instance variable updates like a.b = x, there is a dotted lookup and store to the instance dictionary.

    You can make those containers invoke arbitrary code on the lookup or store. Python’s property provides this capability to new-style classes. The exec and eval operations let you specify a custom dict that can provide this capability to regular assignments. In both cases, you are in complete control of what happens upon assignment.

    Summary: Lookup and store behaviors are controllable through the target of the assignment rather than the object being assigned.

    Example:

    from collections import namedtuple
    
    CallbackVar = namedtuple('CallbackVar', ['change_callback', 'read_callback'])
    
    class CallbackDict(dict):
        'Variant of dict that does callbacks for instances of CallbackVar'
        def __getitem__(self, key):
            value = dict.__getitem__(self, key)
            if isinstance(value, CallbackVar):
                return value.read_callback(key)
        def __setitem__(self, key, value):
            try:
                realvalue = dict.__getitem__(self, key)
                if isinstance(realvalue, CallbackVar):
                    return realvalue.change_callback(key, value)
            except KeyError:
                pass
            return dict.__setitem__(self, key, value)
    
    stmts = '''
    x = CallbackVar(setter, getter)     # Attach getter() and setter() to "x"
    x = 1                               # Invoke the setter()
    x                                   # Invoke the getter()
    '''
    
    def getter(key):
        print 'Getting', key
        return 42
    
    def setter(key, value):
        print 'Setting', key, 'to', value
    
    exec stmts in globals(), CallbackDict()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to create a class that creates and manages log files. I
motivation: I would like to create a utility class so that instead of having
I would like create my own collection that has all the attributes of python
The HttpForbiddenHandler Class is sealed however I'd like to create a class that behaves
I would like to create a class that effectively does this (mixing a little
I would like to create a singleton class that is instantiated once in each
I would like to create a LoadingDialog class that could be used by ANY
I would like to create a class that describes a file resource and then
I would like to create a Javascript class that I can use like so:
I would like to create a class with properties that have subproperties... In other

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.