273

Suppose I have a python object x and a string s, how do I set the attribute s on x? So:

>>> x = SomeObject()
>>> attr = 'myAttr'
>>> # magic goes here
>>> x.myAttr
'magic'

What's the magic? The goal of this, incidentally, is to cache calls to x.__getattr__().

0

5 Answers 5

378
setattr(x, attr, 'magic')

For help on it:

>>> help(setattr)
Help on built-in function setattr in module __builtin__:

setattr(...)
    setattr(object, name, value)
    
    Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
    ``x.y = v''.

However, you should note that you can't do that to a "pure" instance of object. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.

Sign up to request clarification or add additional context in comments.

7 Comments

Careful, however, this doesn't work in your scenario where you're creating an instance of object().
Absolutely right, it doesn't. I conveniently ignored that. I would strongly urge the O.P. to never make instances of object like that.
Damn shame it doesn't work in all cases, as that would be really useful, for example, for adding the dirty attribute to user input...
@Brice: setattr works in almost all cases. For efficiency and other reasons, 'object' is programmed so that you cannot add extra attributes to it. You can do this with your own class with the __slots__ attribute.
This does not work on int as well. Can you explain why? (is it on all __builtin__'s?
|
67

Usually, we define classes for this.

class XClass( object ):
   def __init__( self ):
       self.myAttr= None

x= XClass()
x.myAttr= 'magic'
x.myAttr

However, you can, to an extent, do this with the setattr and getattr built-in functions. However, they don't work on instances of object directly.

>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'

They do, however, work on all kinds of simple classes.

class YClass( object ):
    pass

y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr

4 Comments

Any insight on why this does not work with instances of object()?
@meawoppl You should ask that as a new question
can I do this with Modules, instead of Classes?
The link in @jalanb's comment is 404.
23

let x be an object then you can do it two ways

x.attr_name = s 
setattr(x, 'attr_name', s)

3 Comments

This doesn't always work
@MarkRucker if x is user defined object, it should work. but with something which comes with python, it won't. What did not work for you ?
I was just leaving a note for people in the future that there are unaddressed limitations with this answer. For those who need to know, these limitations are addressed in the two answers above this.
2

Also works fine within a class:

def update_property(self, property, value):
   setattr(self, property, value)

Comments

-2

If you want a filename from an argument:

import sys

filename = sys.argv[1]

file = open(filename, 'r')

contents = file.read()

If you want an argument to show on your terminal (using print()):

import sys

arg = sys.argv[1]

arg1config = print(arg1config)

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.