2

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 !

Community
  • 1
  • 1
Kobz
  • 469
  • 6
  • 17
  • 2
    See: http://stackoverflow.com/questions/2441796/how-to-discover-table-properties-from-sqlalchemy-mapped-object/2448930#2448930 – Thomas Orozco Jul 17 '14 at 08:57
  • I am looking for the same thing in python3 – niklas Jul 21 '16 at 22:14
  • Does this answer your question? [Getting attributes of a class](https://stackoverflow.com/questions/9058305/getting-attributes-of-a-class) – djvg Feb 23 '22 at 09:03

0 Answers0