[Python] Adding metadata (annotations) to python variables

Discussão em 'Python' iniciado por Stack, Março 18, 2025.

  1. Stack

    Stack Membro Participativo

    I have a sqlalchemy class User which inherits from Model.

    class Model:
    @declared_attr
    def __tablename__(self):
    return self.__name__.lower()

    _id = Column(Integer, primary_key=True, autoincrement=True)
    in_utc = Column(BigInteger, default=time())
    out_utc = Column(BigInteger, default=config['MAX_UTC'])

    def to_dict(self):
    return {k: v for k, v in vars(self).items() if not isinstance(v, InstanceState)}

    class User(declarative_base(), Model):
    email = Column(String)
    password = Column(String)
    name = Column(String)


    The reason for the parent class is to add some columns that are common across the tables and also the to_dict() method which creates a dictionary from the columns.

    However I do not want the password column to be included when calling user.to_dict().

    Is there any way to annotate the password Column (like in Java reflection) so that to_dict() knows to ignore it?

    For example:

    class User(declarative_base(), Model):
    email = Column(String)

    [IgnoredInOutput()]
    password = Column(String)

    name = Column(String)


    I've now overridden to_dict in the User class to remove the password column for this model.

    Continue reading...

Compartilhe esta Página