Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to get all possible Python class variables, including ones without values?

I'm creating a class to represent a query, like this:

class Query:
    height: int
    weight: int
    age: int
    name: str
    is_alive: bool = True

As you can see, some variables start off initialized with defaults, others don't.

I want to implement chainable setters like so

    def of_height(self, height):
        self.height = height
        return self

    def with_name(self, name):
        self.name = name
        return self

    ...

The goal is to call this from several places in the project like so:

q = Query()
q.of_height(175).with_name("Alice")

Then I want to call a q.validate() that checks if any fields were not set, before calling an API with this query.

I can't figure out a way to dynamically check all possible variables, set or not, to check if any were left unset. Ideally, I don't want to implement a validate that has to be changed every time I add a possible query dimension in this class.

like image 881
Antrikshy Avatar asked Dec 02 '25 17:12

Antrikshy


1 Answers

The variable annotations collected during class body execution are stored in an __annotations__ attribute which you can use.

>>> Query.__annotations__
{'height': int, 'weight': int, 'age': int, 'name': str, 'is_alive': bool}

This is documented in the datamodel under the "Custom classes" section.

Usually, you would not access this attribute directly but use inspect.get_annotations instead, which provides a few conveniences.

like image 140
wim Avatar answered Dec 05 '25 10:12

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!