Skip to content

1st August 2022



Python Snippets

  • New: Initialize a dataclass with kwargs.

    If you care about accessing attributes by name, or if you can't distinguish between known and unknown arguments during initialisation, then your last resort without rewriting __init__ (which pretty much defeats the purpose of using dataclasses in the first place) is writing a @classmethod:

    from dataclasses import dataclass
    from inspect import signature
    class Container:
        user_id: int
        body: str
        def from_kwargs(cls, **kwargs):
            # fetch the constructor's signature
            cls_fields = {field for field in signature(cls).parameters}
            # split the kwargs into native ones and new ones
            native_args, new_args = {}, {}
            for key, value in kwargs.items():
                if key in cls_fields:
                    native_args[key] = value
                    new_args[key] = value
            # use the native ones to create the class ...
            ret = cls(**native_args)
            # ... and add the new ones by hand
            for new_key, new_value in new_args.items():
                setattr(ret, new_key, new_value)
            return ret


    params = {'user_id': 1, 'body': 'foo', 'bar': 'baz', 'amount': 10}
    Container(**params)  # still doesn't work, raises a TypeError
    c = Container.from_kwargs(**params)
    print(  # prints: 'baz'
  • New: Replace a substring of a string.

    txt = "I like bananas"
    x = txt.replace("bananas", "apples")

Operating Systems


Linux Snippets


  • New: Introduce pipx.

    Pipx is a command line tool to install and run Python applications in isolated environments.

    Very useful not to pollute your user or device python environments.

    Install it with:

    bash pip install pipx