+3  A: 

Python doesn't have one built in, but you can define your own:

def setdefaultattr(obj, name, value):
    if not hasattr(obj, name):
        setattr(obj, name, value)
    return getattr(obj, name)
Ned Batchelder
What about `def setdefaultattr(o,n,v): return setdefault(o.__dict__, n, v)`? That wouldn't work on classes with slots though.
Georg
+1  A: 
vars(obj).setdefault(name, value)
gnibbler
So vars() just returns obj.__dict__?
Ross Rogers
( I do prefer the syntax of var() to obj.__dict__ )
Ross Rogers
@Ross sure. see `help(vars)`
gnibbler
Yup, it does: >>> class Foo(object): ... def __init__(self): self.x = 'foo' ... >>> f = Foo() >>> vars(f) is f.__dict__ True
Mike Hordecki
Aww, no code blocks in comments.
Mike Hordecki
+1 This is a very elegant solution!
jathanism
From python docs **Note The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined.**
nosklo
@noskio, That is certainly the case for `vars()` with no parameters as this returns `locals()`. Attempting to change `locals()` does not work. However there seems to be a contradiction with the builtin docs saying that `vars(obj)` is equivalent to `obj.__dict__` as `obj.__dict__` can be modified.
gnibbler
+4  A: 

Note that the currently accepted answer will, if the attribute doesn't exist already, have called hasattr(), setattr() and getattr(). This would be necessary only if the OP had done something like overriding setattr and/or getattr -- in which case the OP is not the innocent enquirer we took him for. Otherwise calling all 3 functions is gross; the setattr() call should be followed by return value so that it doesn't fall through to return getattr(....)

According to the docs, hasattr() is implemented by calling getattr() and catching exceptions. The following code may be faster when the attribute exists already:

def setdefaultattr(obj, name, value):
    try:
        return getattr(obj, name)
    except AttributeError:
        setattr(obj, name, value)
    return value
John Machin
+1 for EAFP (exception catching)
ΤΖΩΤΖΙΟΥ
+1  A: 

Don't Do This.

Please.

Use __init__ to provide default values. Please. That's the Pythonic way.

class Foo( object ):
    def __init__( self ):
        self.bar = 'bah'

This is the normal, standard, typical approach. There's no compelling reason to do otherwise.

S.Lott
You're right. Shame on me :-) I should just go fix the __init__ function.
Ross Rogers
@Ross Rogers: Please do.
S.Lott