Skip to content

Latest commit

 

History

History
54 lines (40 loc) · 1.71 KB

20220909170243.md

File metadata and controls

54 lines (40 loc) · 1.71 KB

freeze a portion of a function with partial()

functools.partial() lets you put a basic wrapper around ("freeze") an existing function so that you can set a default value where there normally wouldn't be one.

Here we make our own print() defaulting the "end" keyword to a comma (instead of the default newline)

>>> from functools import partial
>>> print_no_newline = partial(print, end=', ')
>>> for _ in range(3): print('test')
...
test
test
test
>>> for _ in range(3): print_no_newline('test')
...
test, test, test, >>>

Another example ...

Explore how PyTorch uses functools.partial for streamlined and reusable dataclass method definitions.

✨ Key Takeaway: functools.partial allows you to "freeze" certain arguments of a function, creating tailored variants.

🔍 In the example below synthesize_equality is tailored for the __eq__ and __ne__ methods, demonstrating how partial can simplify and focus your code:

This approach not only makes your code more concise but also leverages the power of Python's functions being 'first-class objects'. 💡

It's quite fascinating how the generated callables are then stored in a dictionary, demonstrating Python's flexible and dynamic nature. 🐍 😍

# pytorch/torch/jit/_dataclass_impls.py

def synthesize_equality(cls, name: str, converse: str) -> ParsedDef:
    return synthesize_comparison(
        cls,
        name,
        allow_eq=True,
        raise_on_none=False,
        inner=[f"if val1 {converse} val2: return False"],
    )

...
...

DATACLASS_MAGIC_METHODS: Dict[str, Callable] = {
    ...
    "__eq__": partial(synthesize_equality, name="__eq__", converse="!="),
    "__ne__": partial(synthesize_equality, name="__ne__", converse="=="),
}

#functools