5

I am learning Web Development in Flask. I am using SQLAlchemy. A typical database object is structured like so:

class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    default = db.Column(db.Boolean, default=False, index=True)
    permissions = db.Column(db.Integer)
    users = db.relationship('User', backref='role', lazy='dynamic')

    def __repr__(self):
        return '<Role %r>' % self.name

My question is, are these all class variables or object variables? They are outside the __init__ so it would seem they are class variables, that seems odd though. Any pointers on this would be great! Thanks!

1
  • It looks different from regular Python class code, but those are indeed instance (object) variables. Perhaps someone who knows Flask at a deeper level could give you more info about why that is. My guess it that is has to do with the object's inheritance. Commented Apr 17, 2017 at 7:21

1 Answer 1

8

The fields with type Column in Role are indeed class variables. But they would be replaced with InstrumentedAttribute during Role construction, which occurred in declarative.aqi.DeclarativeMeta.__init__()

This is why we define Role inherited from Base with metaclass declarative.aqi.DeclarativeMeta (the return value of declarative_base())

The InstrumentedAttribute is a data descriptor, which defined __get__ and __set__ applied to instance dictionary. As a result, we could use them to do operation through instance.

In the following example, r.name is a data descriptor, r.name = 'hello' is equivalent to Role.name.__set__(r, 'hello') -> r.__dict__['name'] = 'hello'

r = Role()
r.name = 'hello'
Sign up to request clarification or add additional context in comments.

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.