Setting attributes of a class during construction from **kwargs

Posted by Carson Myers on Stack Overflow See other posts from Stack Overflow or by Carson Myers
Published on 2010-05-28T04:07:22Z Indexed on 2010/05/28 4:11 UTC
Read the original article Hit count: 304

Python noob here,

Currently I'm working with SQLAlchemy, and I have this:

from __init__ import Base
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.types import Integer, String
from sqlalchemy.orm import relationship

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    username = Column(String, unique=True)
    email = Column(String)
    password = Column(String)
    salt = Column(String)
    openids = relationship("OpenID", backref="users")

User.__table__.create(checkfirst=True)

#snip definition of OpenID class

def create(**kwargs):
    user = User()
    if "username" in kwargs.keys():
        user.username = kwargs['username']
    if "email" in kwargs.keys():
        user.username = kwargs['email']
    if "password" in kwargs.keys():
        user.password = kwargs['password']

    return user

This is in /db/users.py, so it would be used like:

from db import users
new_user = users.create(username="Carson", password="1234")
new_user.email = "[email protected]"
users.add(new_user) #this function obviously not defined yet

but the code in create() is a little stupid, and I'm wondering if there's a better way to do it that doesn't require an if ladder, and that will fail if any keys are added that aren't in the User object already. Like:

for attribute in kwargs.keys():
    if attribute in User:
        user.__attribute__[attribute] = kwargs[attribute]
    else:
        raise Exception("blah")

that way I could put this in its own function (unless one hopefully already exists?) So I wouldn't have to do the if ladder again and again, and so I could change the table structure without modifying this code.

Any suggestions?

© Stack Overflow or respective owner

Related posts about python

Related posts about class