TIL: Enforcing keyword-only arguments in Python function

Share this post:

You can enforce keyword-only arguments in your functions by adding “*” before the arguments.


def create_node(self, *, node_id, name):

When calling the above defined method, you will call it like:

self.create_node(node_id=1, name="node")

If you call self.create_node(1, "node"), it will raise a TypeError.

I like that it makes my code look clean and makes it self-documenting.

Share this post:

Leave a Comment

Your email address will not be published. Required fields are marked *