Python function parameter type

PEP 695 – Type Parameter Syntax

This PEP specifies an improved syntax for specifying type parameters within a generic class, function, or type alias. It also introduces a new statement for declaring type aliases.

Motivation

PEP 484 introduced type variables into the language. PEP 612 built upon this concept by introducing parameter specifications, and PEP 646 added variadic type variables.

While generic types and type parameters have grown in popularity, the syntax for specifying type parameters still feels “bolted on” to Python. This is a source of confusion among Python developers.

There is consensus within the Python static typing community that it is time to provide a formal syntax that is similar to other modern programming languages that support generic types.

An analysis of 25 popular typed Python libraries revealed that type variables (in particular, the typing.TypeVar symbol) were used in 14% of modules.

Points of Confusion

While the use of type variables has become widespread, the manner in which they are specified within code is the source of confusion among many Python developers. There are a couple of factors that contribute to this confusion.

The scoping rules for type variables are difficult to understand. Type variables are typically allocated within the global scope, but their semantic meaning is valid only when used within the context of a generic class, function, or type alias. A single runtime instance of a type variable may be reused in multiple generic contexts, and it has a different semantic meaning in each of these contexts. This PEP proposes to eliminate this source of confusion by declaring type parameters at a natural place within a class, function, or type alias declaration statement.

Generic type aliases are often misused because it is not clear to developers that a type argument must be supplied when the type alias is used. This leads to an implied type argument of Any , which is rarely the intent. This PEP proposes to add new syntax that makes generic type alias declarations clear.

PEP 483 and PEP 484 introduced the concept of “variance” for a type variable used within a generic class. Type variables can be invariant, covariant, or contravariant. The concept of variance is an advanced detail of type theory that is not well understood by most Python developers, yet they must confront this concept today when defining their first generic class. This PEP largely eliminates the need for most developers to understand the concept of variance when defining generic classes.

When more than one type parameter is used with a generic class or type alias, the rules for type parameter ordering can be confusing. It is normally based on the order in which they first appear within a class or type alias declaration statement. However, this can be overridden in a class definition by including a “Generic” or “Protocol” base class. For example, in the class declaration class ClassA(Mapping[K, V]) , the type parameters are ordered as K and then V . However, in the class declaration class ClassB(Mapping[K, V], Generic[V, K]) , the type parameters are ordered as V and then K . This PEP proposes to make type parameter ordering explicit in all cases.

Читайте также:  Kotlin coroutine scope это

The practice of sharing a type variable across multiple generic contexts creates other problems today. Modern editors provide features like “find all references” and “rename all references” that operate on symbols at the semantic level. When a type parameter is shared among multiple generic classes, functions, and type aliases, all references are semantically equivalent.

Type variables defined within the global scope also need to be given a name that starts with an underscore to indicate that the variable is private to the module. Globally-defined type variables are also often given names to indicate their variance, leading to cumbersome names like “_T_contra” and “_KT_co”. The current mechanisms for allocating type variables also requires the developer to supply a redundant name in quotes (e.g. T = TypeVar(«T») ). This PEP eliminates the need for the redundant name and cumbersome variable names.

Defining type parameters today requires importing the TypeVar and Generic symbols from the typing module. Over the past several releases of Python, efforts have been made to eliminate the need to import typing symbols for common use cases, and the PEP furthers this goal.

Summary Examples

Defining a generic class prior to this PEP looks something like this.

from typing import Generic, TypeVar _T_co = TypeVar("_T_co", covariant=True, bound=str) class ClassA(Generic[_T_co]): def method1(self) -> _T_co: . 

With the new syntax, it looks like this.

Источник

Python Function Parameter Type

Python Function Parameter Type

  1. Python Function Parameter Types
  2. What is a Function in Python
  3. Default and Flexible Arguments in Python
  4. Conclusion

In this Python article, we will learn the function parameter types used in Python. We will also learn how to write a Python function without a parameter.

We will see how we can write a function in Python with one or multiple parameters. We need to understand a function and how to write a function in Python.

Let’s begin by understanding the concepts of parameter types in Python.

Python Function Parameter Types

Python function parameters provide data that the functions use when they are executed. We can specify parameters differently, but not all methods are required in every function.

It depends on the functionalities of the function, and we decide according to the circumstances.

When we do specify parameters, they may be assigned data types, and these types must match with what is expected, or the code will not run properly.

The parameter declaration methods default , **kwargs , and **args are the parameters we work with when working on any function in Python.

But before diving into our main topic, we will first look into the basics of functions so it’s easier to work with function parameters.

Читайте также:  Как использовать rem css

What is a Function in Python

A function in Python can be defined as a list of statements that will be executed when the function is called. We can define a function by using the keyword def and assigning it a name.

In this article, we will be covering the below-mentioned areas one by one with examples.

  1. Writing a function
  2. Function without parameters
  3. Functions with one parameter
  4. A function that returns a value
  5. Multiple arguments, multiple return values

Writing a Function

First, we will write a function of our need, which will work according to our requirements whenever we call it.

Suppose we want a function that takes any number and gives us the square of the number. Know that defining function is easy.

Now, all we need to do is to use the def keyword, followed by the name of our function, followed by parentheses () , and followed by a colon : .

Function Without Parameters

In our scenario, we want a function that squares numbers to name our function square . This is how we can define our square function.

  1. We will define the function
  2. Multiply the number with 2 and assign it to a variable
  3. Print the variable inside the function
  4. Call the function because if we do not call the function, we will not be able to get the output.
def square():  value = 2**2  print(value) 

Remember that we never call the function within the function; we call it outside of the function.

But, what if we want to give different numbers to the function so we can find the square of different numbers according to the situation?

Functions With One Parameter

This is where the parameter comes in handy. We will pass a parameter in the function.

So, whenever we want to know the square of any number, we will call the function and hand over that number to the function.

Within nanoseconds, we will have the square of any value. Let’s try it with an example, and let’s define the square function again with a parameter.

def square(number):   value = number**2  print(value) 

Now, we will call the function and give it some random numbers to see if it gives back the correct squares.

To find the square of 25, we will call our function square and give it the value 25.

Function That Returns a Value

If we do not print the value directly, we want to return it and assign it to another variable. We use the return keyword.

def square(number):  values = number**2  return values 

Now we will assign our function to a variable we have outside the function.

To see the output of the above code, we will print the variable we have created.

Multiple Arguments and Multiple Return Values

  1. How a function accepts more than one parameter
  2. How can we pass multiple arguments to a function
  3. How can we get multiple return values

Let’s do all these with an example. We will define a function that accepts more than one parameter and takes multiple arguments and multiple return values.

def raise_to_power(val, val2):  return val**val2 

Now we call the function and pass two values for the parameters mentioned in the function val, val2 .

Читайте также:  imgExample

Default and Flexible Arguments in Python

Let’s say we are writing a function that takes multiple parameters, and there is also a common value for some of these parameters.

In this case, we would like to call a function without specifying every function. Sometimes, we would like some parameters to have default arguments used when it is not specified otherwise.

  1. How to write a function with a default argument
  2. *args — Flexible arguments allow us to pass any number of arguments in the function.
  3. **kwargs — Keyword arguments

Define a function with a default argument value; in the function header, follow the parameter of interest with an equal sign and a default argument value.

def power(word, pow = 1):  words = word ** pow  return words 

Now we will call our function power , and we will only pass an argument for the parameter word .

The second parameter in the function has a default value of 1 and 3 power 1 = 3 .

Flexible Argument *args in Python Function

When unsure of the number of arguments given to our function, we add a * before the parameter name in the function specification.

Let’s suppose we want to write a function but aren’t sure how many arguments a user will pass. We will define a function that takes int and floats and adds them.

def add_all(*number):  sum_all = 0  # apply for loop to sum all the parameter  for num in number:  sum_all += num  return sum_all 

Now we will call the function and pass some arguments.

Keyword Arguments **kwargs

In the function, before the parameter name declaration, we add two asterisks, ** , when we are unsure of the number of keyword arguments that will be provided in our function.

This will allow the function to access the items appropriately after receiving a dictionary of arguments.

def my_function(**name):  print("The child's last name is " + name["last_name"]) 

Now we call the function and pass some arguments.

my_function(first_name = "Abid", last_name = "Orakzai") 
The child's last name is Orakzai 

Conclusion

Thus, we get to know that there are three different kinds of parameters that the Python function can accept. These are the arbitrary *args , keyword **kwargs , and default parameters .

While keyword arguments allow us to employ any order, default arguments assist us in dealing with the absence of values. Finally, Python’s arbitrary arguments *args come in handy when we don’t know how many arguments we’ll get.

We hope you find this article helpful in understanding the basic idea of function parameter types used in Python.

My name is Abid Ullah, and I am a software engineer. I love writing articles on programming, and my favorite topics are Python, PHP, JavaScript, and Linux. I tend to provide solutions to people in programming problems through my articles. I believe that I can bring a lot to you with my skills, experience, and qualification in technical writing.

Related Article — Python Function

Источник

Оцените статью