Using type prompts in Python improves code readability and maintainability and supports static checking. 1. Basic type prompts such as def greet(name: str, age: int) -> str: return f"Hello, {name}. You are {age} years old." 2. Complex types need to be imported List, Dict, and Optional, such as List[Dict[str, Optional[int]]] represents a dictionary list, the value can be int or None, and the return Optional[str] means that the parameter or return value can be int or str, Python 3.10 can be abbreviated as int | str; 4. Callable[[int, int], int] is used for function parameters, representing a function that accepts two ints and returns int; 5. Type alias can be defined such as Student = Dict[str, int] and Students = List[Student] to enhance readability; 6. Python 3.9 supports the direct use of built-in generics such as list[str], dict[str, int]. Type prompts do not affect the operation, but they help team collaboration and error detection, ultimately improving the quality of the code.
Using Type Hints in Python can make functions clearer and easier to maintain, and also facilitate error detection by static type checking tools such as mypy
. Below is a typical function example with type prompts covering common type usage.

? Basic function type prompt example
def greet(name: str, age: int) -> str: return f"Hello, {name}. You are {age} years old."
-
name: str
means that the parametername
should be of string type. -
age: int
means that the parameterage
should be of integer type. -
-> str
means that the return value of the function is of string type.
? Use complex types (List, Dict, Optional)
from typing import List, Dict, Optional def process_students( students: List[Dict[str, Optional[int]]] ) -> Optional[str]: If not students: return None total = sum(s["age"] for s in students if s["age"] is not None) return f"Total age: {total}"
illustrate:
-
List[Dict[str, Optional[int]]]
: represents a list, each element is a dictionary, the dictionary's key is a string, and the value is an integer orNone
. -
Optional[str]
: equivalent toUnion[str, None]
, indicating that the return value can be a string orNone
.
?Using Union (multiple possible types)
from typing import Union def square_or_repeat(value: Union[int, str]) -> Union[int, str]: if isinstance(value, int): return value ** 2 elif isinstance(value, str): return value * 2 else: raise TypeError("Value must be int or str")
-
Union[int, str]
means that the parameter or return value can beint
orstr
.
?? In Python 3.10, it can be written more concisely:
def square_or_repeat(value: int | str) -> int | str: ...
? Function as parameter (Callable)
from typing import Callable def apply_operation(x: int, y: int, op: Callable[[int, int], int]) -> int: return op(x, y) # Use example result = apply_operation(3, 4, lambda a, b: ab) # Return 7
-
Callable[[int, int], int]
means: a function that accepts twoint
parameters and returnsint
.
? Custom Type Alias
from typing import List, Dict Student = Dict[str, int] Students = List[Student] def average_age(students: Students) -> float: If not students: return 0.0 return sum(s["age"] for s in students) / len(students)
-
Students
is a type alias that improves code readability.
Summary: Common Type Import
from typing import List, Dict, Tuple, Set, Optional, Union, Callable, Any
Or in Python 3.9, the built-in types already support generics (such as list
, dict
), and you can use it directly:
def example(items: list[str]) -> dict[str, int]: return {item: len(item) for item in items}
Basically these common uses. Type prompts don't affect the run, but are very helpful for team collaboration and code quality.

The above is the detailed content of python type hint function example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Python is an efficient tool to implement ETL processes. 1. Data extraction: Data can be extracted from databases, APIs, files and other sources through pandas, sqlalchemy, requests and other libraries; 2. Data conversion: Use pandas for cleaning, type conversion, association, aggregation and other operations to ensure data quality and optimize performance; 3. Data loading: Use pandas' to_sql method or cloud platform SDK to write data to the target system, pay attention to writing methods and batch processing; 4. Tool recommendations: Airflow, Dagster, Prefect are used for process scheduling and management, combining log alarms and virtual environments to improve stability and maintainability.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

UseGuzzleforrobustHTTPrequestswithheadersandtimeouts.2.ParseHTMLefficientlywithSymfonyDomCrawlerusingCSSselectors.3.HandleJavaScript-heavysitesbyintegratingPuppeteerviaPHPexec()torenderpages.4.Respectrobots.txt,adddelays,rotateuseragents,anduseproxie

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces
