home.social

#dailypythontip — Public Fediverse posts

Live and recent posts from across the Fediverse tagged #dailypythontip, aggregated by home.social.

  1. Python Tip #278 (of 365):

    Always include a __init__‍.py file in your Python packages. Even an empty one.

    food_utils
    ├── fruits‍.py
    ├── __init__‍.py
    └── non_fruits‍.py

    A package is a directory that Python treats like a module.

    When you import the package, the module you get back IS the __init__‍.py file:

    >>> import food_utils
    >>> food_utils
    <module 'food_utils' from '/home/trey/food_utils/__init__‍.py'>

    🧵 (1/3)

    #Python #DailyPythonTip

  2. Python Tip #276 (of 365):

    Make self positional-only when accepting "**kwargs".

    This class accepts arbitrary keyword arguments... except for self:

    >>> class Namespace:
    ... def __init__(self, **kwargs):
    ... for name, value in kwargs.items():
    ... setattr(self, name, value)
    ...
    >>> space = Namespace(other=2, self=1)
    Traceback (most recent call last):
    ...
    TypeError: Namespace.__init__() got multiple values for argument 'self'

    🧵 (1/3)

    #Python #DailyPythonTip

Share on Mastodon

Enter the server where you have an account.