Is it possible to get the name of our custom attributes of a class in Python ? For instance, here's my class :
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key = True)
login = db.Column(db.String(100))
password = db.Column(db.String(100))
first_name = db.Column(db.String(100))
last_name = db.Column(db.String(100))
email = db.Column(db.String(100))
age = db.Column(db.Integer)
sex = db.Column(db.String(10))
What I want is to get the list of my class attributes (and only those that I defined !). I was thinking about using dir(self)
and filtering on those not starting with __
but it's not really revelant because there are other fields who are built-in such as metadata
, query
and so on.
I saw a function getattr (or getattribute)
but it's only for a given field.
I don't want to use a dict of keys because it have to stay generic and I don't want to modify the dict everytime I add a field.
As I'm using SqlAlchemy ORM
, I got this when trying self.__dict__
:
{'_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x7ffbcf252050>}
I also tried a lot of things such as those described here : Python dictionary from an object's fields but nothing worked.
Does anyone have a solution ?
Thanks !