Is there a Pythonic way to type a function parameter to a specific django model object?


Let’s say I have a model like this:

class Foo():
   name = models.CharField()

And a function like this:

def update_foo_name(foo_object): = "New Name"

Is there a way to enforce typing on update_foo_name(), so that only a valid object of Foo can be passed here?

Ie something like update_foo_name(foo_object: Foo.objects).

Apologies if this has already been asked, and thank you in advance for any responses!


a pythonic way should be

class Foo():
    name = models.CharField()
    def change_name(self, new_name: str): = new_name

if you really wanna do it out of Foo scope, in a global function or from a Bar class for example, a way to guarantee is:

class Bar()

    def method_to_change_foo_name_for_any_reason(self, foo: Foo):
        assert isinstance(foo, Foo), TypeError("Not a Foo object") = "New name that bar gives to foo"

Answered By – Luid Duarte

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published