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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T05:46:22+00:00 2026-06-01T05:46:22+00:00

How does one build a function that can set an arbitrary value within a

  • 0

How does one build a function that can set an arbitrary value within a dictionary or object? Or in other words, a function that can set any value passed into it.

For example, suppose you have a dictionary like this:

my_dict = {
  'foo' : 'bar', 
  'subdict':{
    'sub1' : 1,
    'sub2' : 2
  }
}

I would like to create a setter function to be used like this:

x = 'x'
# I want to be able to set normal dictionary items
setter(lambda val: val['foo'], my_dict, x)

# And also set subdictionary items
setter(lambda val: val['subdict']['sub1'], my_dict, x)

# Setting items that don't exist would be great too
setter(lambda val: val['new_item'], my_dict, x)

# If my_dict was a class, I'd like to use the same function, like this
setter(lambda val: val.myproperty, my_dict, x)

# Would also be cool if it worked with lists
my_list = [1, 2]
setter(lambda val: val[1], my_list, x)

I don’t seen an obvious way to do this. The naive way below clearly does not work:

def setter(get_attr_func, param, x):
  # This doesn't work, but I'd like something like it
  get_attr_func(param) = x

I could use the setattr to build something that works for attributes on classes. I could build something else that works for items in dictionaries. But I have no idea how you would do it for sub-dictionaries or sub-objects.

The answer does not have to be in this exact form. Rather, I just want to write a function that sets an arbitrary attribute/item within an object hierarchy.

  • 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-01T05:46:23+00:00Added an answer on June 1, 2026 at 5:46 am

    I decided this was an interesting problem. Primarily, this class collects item or attribute names when you try to get items or attributes from it. It can then use those collected operations to get or set the corresponding value on an object hierarchy. It also has a couple of convenience methods for making a set_to_x function like the one in your example.

    The class:

    class LocationProxy(object):
        def __init__(self, ops = None):
            self.ops = ops or []
        def __getitem__(self, item):
            self.ops.append((True, item))
            return self
        def __getattr__(self, attr):
            self.ops.append((False, attr))
            return self
        @staticmethod
        def iterativeget(obj, ops):
            for isitem, key in ops:
                obj = obj[key] if isitem else getattr(obj, key)
            return obj
        def get(self, obj):
            return self.iterativeget(obj, self.ops)
        def set(self, obj, value):
            isitem, key = self.ops[-1]
            obj = self.iterativeget(obj, self.ops[:-1])
            if isitem:
                obj[key] = value
            else:
                setattr(obj, key, value)
        def set_from_object(self, obj):
            return lambda value: self.set(obj, value)
        def set_to_value(self, value):
            return lambda obj: self.set(obj, value)
        @staticmethod
        def object_value_setter(obj, value):
            return lambda location: location.set(obj, value)
        @staticmethod
        def object_setter(obj):
            return lambda location, value: location.set(obj, value)
        @staticmethod
        def value_setter(value):
            return lambda location, obj: location.set(obj, value)
    

    Let’s prepare some data and make some setter functions:

    # since you can't set attributes on a normal dict, use a subclass
    class MyDict(dict): pass
    
    my_dict = MyDict({
      'foo' : 'bar',
      'subdict':{
        'sub1' : 1,
        'sub2' : 2
      }
    })
    
    my_list = [1, 2]
    
    x = 'x'
    
    # we're going to set multiple things in my_dict to x, let's not repeat ourselves
    set_my_dict_to_x = LocationProxy.object_value_setter(my_dict, x)
    
    # we'll use set_to_x as you used it later on my_list
    set_to_x = LocationProxy.value_setter(x)
    

    Now let’s test them:

    # you can assign a name to a setter to use multiple times
    foosetter = LocationProxy()['foo']
    
    # set normal dictionary items
    set_my_dict_to_x(foosetter)
    
    # And also set subdictionary items
    set_my_dict_to_x(LocationProxy()['subdict']['sub1'])
    
    # Set items that don't exist
    set_my_dict_to_x(LocationProxy()['new_item'])
    
    print 'my_dict', my_dict
    
    # my_dict is a class, use the same function
    set_my_dict_to_x(LocationProxy().myproperty)
    
    print 'myproperty', my_dict.myproperty
    
    # it works with lists
    set_to_x(LocationProxy()[1], my_list)
    
    print 'my_list', my_list
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

does one perform better over the other in terms of indexing/quering etc ? e.g.
How does one test a method that does some interactions with the local D-Bus
How does one obtain programmatically a reference to the object of which a FieldInfo
I am looking for a SQL Server function that I can supply 3 primary
within a form I have a section that allows the user to build out
In bash one can escape arguments that contain whitespace. foo a string This also
I'm planning to build an application that must allow the user to set up
Does Java have a built-in Antivirus? One of my friends told me there is
How does one compare single character strings in Perl? Right now, I'm tryin to
How does one convert from an int or a decimal to a float in

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.