pythonic way of writing a library function which accepts multiple types?

  • Last Update :
  • Techknowledgy :

This module defines several types that are subclasses of pre-existing standard library classes which also extend Generic to support type variables inside []. These types became redundant in Python 3.9 when the corresponding pre-existing classes were enhanced to support [].,The module defines the following classes, functions and decorators.,This decorator is itself not available at runtime. It is mainly intended to mark classes that are defined in type stub files if an implementation returns an instance of a private class:,This works as class or function decorator. With a class, it applies recursively to all methods defined in that class (but not to methods defined in its superclasses or subclasses).

def greeting(name: str) - > str:
   return 'Hello ' + name
Vector = list[float]

def scale(scalar: float, vector: Vector) - > Vector:
   return [scalar * num
      for num in vector
   ]

# typechecks;
a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
from collections.abc
import Sequence

ConnectionOptions = dict[str, str]
Address = tuple[str, int]
Server = tuple[Address, ConnectionOptions]

def broadcast_message(message: str, servers: Sequence[Server]) - > None:
   ...

   # The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
      message: str,
      servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) - > None:
   ...
from typing
import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)
def get_user_name(user_id: UserId) - > str:
   ...

   # typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck;
an int is not a UserId
user_b = get_user_name(-1)
# 'output'
is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)

Suggestion : 2

Hence the proper way to represent more than one return data type is

from typing
import Union

def foo(client_id: str) - > Union[list, bool]

But do note that typing is not enforced. Python continues to remain a dynamically-typed language. The annotation syntax has been developed to help during the development of the code prior to being released into production. As PEP 484 states, "no type checking happens at runtime."

>>> def foo(a: str) - > list:
   ...
   return ("Works")
      ...
      >>>
      foo(1)
'Works'

As you can see I am passing a int value and returning a str. However the __annotations__ will be set to the respective values.

>>> foo.__annotations__ 
{'return': <class 'list'>, 'a': <class 'str'>}

In case anyone landed here in search of "how to specify types of multiple return values?", use Tuple[type_value1, ..., type_valueN]

from typing
import Tuple

def f() - > Tuple[dict, str]:
   a = {
      1: 2
   }
b = "hello"
return a, b

The native way to describe a "either A or B" type hint is Union (thanks to Bhargav Rao):

def foo(client_id: str) - > Union[list, bool]:

Or, starting with Python 3.10 and beyond, using the | operator:

def foo(client_id: str) - > list | bool:

Python 3.10 (use |): Example for a function which takes a single argument that is either an int or str and returns either an int or str:

def func(arg: int | str) - > int | str:
   ^
   ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
   type of arg
return type

Python 3.5 - 3.9 (use typing.Union):

from typing
import Union
def func(arg: Union[int, str]) - > Union[int, str]:
   ^
   ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
   type of arg
return type

In base Python simply do:

def foo(x: (list, str)):
   pass

Suggestion : 3

Starting here? This lesson is part of a full-length tutorial in using Python for Data Analysis. Check out the beginning.,Methods of dictionaries, specifically .keys() and .values(), The "length" of the dictionary is the number of key-value pairs that are stored in the dictionary. In this case, the length is 2. ,You should also take a minute to understand how Python is evaluating the second answer. Everything is executed from the inside out, similar to the order of operations in math (remember PEMDAS?). Here's the order in which Python runs the above line of code:

city_population = {
   'Tokyo': 13350000,
   # a key - value pair 'Los Angeles': 18550000,
   'New York City': 8400000,
   'San Francisco': 1837442,
}
city_population.keys()
['New York City', 'San Francisco', 'Los Angeles', 'Tokyo']
type(city_population.keys())
list
city_population.keys()[2]

Suggestion : 4

Write a function that takes a small, fixed number of arguments and produces a single result.,Write a function that takes a small, fixed number of arguments and produces a single result. ,Functions are most useful when they can operate on different data.,Fill in the blanks to create a function that takes a list of numbers as an argument and returns the first negative value in the list. What does your function do if the list is empty?

def print_greeting():
   print('Hello!')
print_greeting()
Hello!
def print_date(year, month, day):
   joined = str(year) + '/' + str(month) + '/' + str(day)
print(joined)

print_date(1871, 3, 19)
1871 / 3 / 19
def average(values):
   if len(values) == 0:
   return None
return sum(values) / len(values)

Suggestion : 5

Updated: January 28, 2021

def function_name(data):
def function_name(data_1, data_2):
def multiply_values
def multiply_values(x, y):
def multiply_values(x, y):
   z = x * y
return z
def multiply_values(x, y):
   ""
"Calculate product of two inputs. 

Parameters
-- -- -- -- --
x: int or float
y: int or float

Returns
-- -- --
z: int or float ""
"
z = x * y
return z

Suggestion : 6

Write a function that takes a small, fixed number of arguments and produces a single result.,Write a function that takes a small, fixed number of arguments and produces a single result. ,Break programs down into functions to make them easier to understand.,Break programs down into functions to make them easier to understand.

def print_greeting():
   print('Hello!')
print_greeting()
Hello!
def print_date(year, month, day):
   joined = str(year) + '/' + str(month) + '/' + str(day)
print(joined)

print_date(1871, 3, 19)
1871 / 3 / 19
print_date(month = 3, day = 19, year = 1871)