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

Time:05-04

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):
   foo_object.name = "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!

CodePudding user response:

a pythonic way should be

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

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")
        foo.name = "New name that bar gives to foo"
        foo.save()

CodePudding user response:

Python does not do static type checking, see details here.


It means that this:

def set_foo_name(foo: Foo):
    foo.name="New Name"

doesn't raise an exception when you pass in an object of some other type.

You'll have to run assert isinstance(foo, Foo) as per Luid's answer.

  • Related