Skip to content

Python function

ghdrako edited this page Jun 30, 2023 · 13 revisions

Indepotent function

from copy import copy
def better_total(values: list, new_value: int) -> int:
  temp_list = copy(values)  # makes a copy of the values parameter, creating a new list variable temp_list independent of the one referenced by the values_2 list.
  temp_list.append(new_value)
  return sum(temp_list)

values_2 = [1, 2, 3]
total_2 = better_total(values_2, 4)
print(f"values_2 unchanged: {values_2}")
print(f"total_2 is as expected: {total_2}")

# output
values_2 unchanged: [1, 2, 3]
total_2 is as expected: 10

Reurning multiple values

when we appear to return multiple values in a function definition, we’re returning a single vari able that is a tuple object consisting of these values. W You can apply the tuple unpacking technique to using the multiple values returned from a function, which is a concise,

from statistics import mean, stdev 
def generate_stats(measures):
  measure_mean = mean(measures)  
  measure_std = stdev(measures)  
  return measure_mean, measure_std

m_mean, m_std = generate_stats(measures)
from typing import Tuple
def split_fullname(full_name: str) -> Tuple[str, str, str]:
  fname = mname = lname = ""
  parts = full_name.split()
  if len(parts) >= 1:
    fname = parts[0]
  if len(parts) >= 2:
    mname = parts[1]
  if len(parts) == 3:
    lname = parts[2]
  if not lname:
    mname, lname = (lname, mname)
  return (fname, mname, lname)
# use case
fname, mname, lname = split_fullname("John James Smith")

*arg

def stringify(*items): 
  print(f"got {items} in {type(items)}")  
  return [str(item) for item in items]

all the positional arguments are packed into a tuple object named items. Thus, we can apply any tuple-related techniques to items.

def stringify_a(item0, *items):
  print(item0, items)
def full_name(fname, *names):
  return " ".join([fname, *names]

**kwarg

the variable number of keyword arguments is packed into a single object: dict.

def create_report(name, **grades):
  for subject, grade in grades.items():

Order placingparameters

def example(arg0, arg1, *args, kwarg0, kwarg1, **kwargs):
  pass

docstring

>>> help(isinstance)
>>> print(isinstance.__doc__)

A function’s docstring in Google style. Three elements are required: summary, parameters, and return value. If the function raises any exception, it needs to be specified too.

def example(param0, param1):
  """ 
  This is an example function docstring.
  Args:
    param0:
    param1:
  Returns:
  Describe the return value Raises:
  Describe any Exception 
  """ 

A function’s docstring in the reST style used by PyCharm. The key elements are the same as docstrings in other styles: summary, parameters, return value, and exceptions (where applicable).

def example(param0, param1):
  """ 
  This is an example function docstring.
    :param param0:
    :param param1:
    :return:
    :raises: 
  """
def quotient(dividend, divisor, taking_int=False):
  """  
  Calculate the product of two numbers with a base factor.
  :param dividend: int | float, the dividend in the division  
  :param divisor: int | float, the divisor in the division  
  :param taking_int: bool, whether only taking the integer part of  ➥ the quotient; default: False, which calculates the  ➥ precise quotient of the two numbers  

  :return: float | int, the quotient of the dividend and divisor
  :raises: ZeroDivisionError, when the divisor is 0  
  """  
  if divisor == 0:
    explicitly  raise ZeroDivisionError("division by zero")  
  result = dividend / divisor  
  if taking_int:
    result = int(result)  
  return result
def get_mean(data):
 return "mean of the data" 
def get_min(data):
 return "min of the data" 
def get_max(data):
 return "max of the data" 
def process_data(data, action):
 if action == "mean":
 processed = get_mean(data)  elif action == "min":
 processed = get_min(data)  elif action == "max":
 processed = get_max(data)  else:
 processed = "error in action"  return processed
actions = {"mean": get_mean, "min": get_min, "max": get_max} 
def fallback_action(data):  
  return "error in action" 
def process_data(data, action):
  calculation = actions.get(action, fallback_action)  
  processed = calculation(data)  
  return processed
numbers_str = ["1.23", "4.56", "7.89"] 
numbers = list(map(float, numbers_str)) 
assert numbers == [1.23, 4.56, 7.89]

The map function can take more than one iterable. When there are multiple iterables, the items from each iterable are sent to the mapping function based on the order of the iterables.

numbers_list = [float(x) for x in numbers_str

Test

Clone this wiki locally