1

When I do the following:

def Welcome(email, temporaryPassword):
    model = object()
    model.TemporaryPassword = temporaryPassword
    model.Email = email

I get an error:

AttributeError: 'object' object has no attribute 'TemporaryPassword'

How do I dynamically create an object like I am doing?

1

3 Answers 3

1

use lambda object : ( http://codepad.org/ITFhNrGi )

def Welcome(email, temporaryPassword):
    model = type('lamdbaobject', (object,), {})()
    model.TemporaryPassword = temporaryPassword
    model.Email = email
    return model


t = Welcome('[email protected]','1234')
print(str(t.TemporaryPassword))
Sign up to request clarification or add additional context in comments.

Comments

1

you can define a dummy class first:

class MyObject(object):
    pass

obj = MyObject()
obj.TemporaryPassword = temporaryPassword

Comments

1

If you only use the object as a data structure (i.e. no methods) you can use a namedtuple from the collections package:

from collections import namedtuple
def welcome(email, tmp_passwd):
    model = namedtuple('MyModel', ['email', 'temporary_password'])(email, tmp_passwd)
    ...

By the way, if your welcome function only creates the object and returns it, there is no need for it. Just:

from collections import namedtuple
Welcome = namedtuple('Welcome', ['email', 'temporary_password'])

ex = Welcome('[email protected]', 'foobar')
print ex.email
print ex.temporary_password

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.