You probably know that Python is a high level programming language, but have you ever wondered what does it mean? In computer science terms, a high level language is a programming language which the program logic is closer to human language. It means that a programmer has a chance to express his ideas in a more natural way, in English for example. The program logic is less dependent on the underlying machine architecture and thus the programming becomes easier.
In this article I will show how to use variable number of keyword arguments in Python 3.5+. I will demonstrate the syntax and structure of the keyword-only argument and why it can be useful in various situations.
Keyword-only arguments are type of named parameters which can only be accessed via keyword. They were introduced in Python 3.5 and they can be used in functions and methods. First, let’s see a simple function that uses a positional argument:
def my_function ( arg1 , arg2 ): print ( 'Keyword Only Arguments' ) print ( "Hello" ) print ( "World" ) my_function ( 1 , 2 ) my_function ( 1 , 2 , 3 )
We can see that you can omit the first two parameters because one of them is assigned default value. When you run the program you will receive the following output:
Hello World Keyword Only Arguments
As you can see, Python doesn’t complain if you skip the first two parameters despite the fact that they are marked as required. You can also see that the keyword-only argument doesn’t show up on the output. Let’s change our function so it uses keyword argument:
def my_function ( arg1 , keyword_arg2 = None ): print ( 'Keyword Only Arguments' ) print ( "Hello" ) print ( "World" ) my_function () my_function ( 1 ) my_function ( 1 , 2 ) my_function ( 1 , 2 , 3 , keyword_arg2 = 4 )
Now when you run the program you will see that you cannot access keyword-only argument without specifying its name:
Hello World Keyword Only Arguments TypeError : 'NoneType' object is not callable . Hello World Keyword Only Arguments TypeError : 'NoneType' object is not callable . Keyword Only Arguments Hello World Keyword Only Arguments C:UsersPawelDesktopscript.py:7: TypeError: 'NoneType' object is not callable
This new feature allows for better control over function parameters, which makes it possible to simplify function calls and avoid errors. Also, I find it very convenient to be able to access all function parameters via keyword like this: func(keyword_arg1 = 1, keyword_arg2 = 2, keyword_arg3 = 3) . However, if you use the keyword-only parameter inside your function you must remember that you cannot access it by position, so be careful when using it!