what is it?
functools.partial(func, /, *args, **keywords)
returns a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords
in english (thanks danny):
- makes a new version of a function with one or more arguments already filled in
- new version of a function documents itself
example
from functools import partial
basetwo = partial(int, base=2)
basetwo('10010')
# returns 18django specific uses
reusable fields without subclassing
from functools import partial
from django.db import models
CreatedAtField = partial(
models.DateTimeField,
default=timezone.now,
help_text="When this instance was created.",
)
class Book(models.Model):
...
created_at = CreatedAtField()
class Author(models.Model):
...
created_at = CreatedAtField()upload_to callables for FileField
from functools import partial
from django.db import models
def user_upload_to(instance, filename, category):
return f"users/{instance.id}/{category}/{filename}"
class User(models.Model):
...
profile_picture = models.ImageField(
upload_to=partial(user_upload_to, category="profile"),
)
background_picture = models.ImageField(
upload_to=partial(user_upload_to, category="background"),
)