Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Functions

Type Hints on Python Functions: Parameters, Returns, None and Collections

A type hint is a label on a jar: it says what belongs inside but stops nothing. Hint parameters and returns, -> None, str | None, list[str] and dict[str, int], see add("2", "3") print 23, and read hints back with __annotations__.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Functions

What you will learn

  • Hint a function's parameters and return value, including -> None and defaults
  • Use str | None for a value that might be missing, and check for None
  • Hint what is inside a list or dict with list[str] and dict[str, int]
  • Explain why Python does not enforce hints and who reads them instead

Before you start

  • Python Functions: Parameters, Return, Scope, *args and **kwargs
  • Python Lists, Tuples, Sets and Dicts

Until now, you had to read the body of a function to know what it expects. A type hint puts that on the very first line.

Think about a jar in your kitchen with a label that says sugar. Everybody knows what belongs inside without opening it. But the label doesn't guard anything. Pour salt in and the jar takes it, and you only find out later, when you taste your tea. That's a type hint: it tells everyone what should go in, but it doesn't stop anything.

You already know hints on variables, like name: str = "Alice", from lists, tuples, sets and dicts. A function asks the same question in two places: what goes in, and what comes out.

Parameter hints and return hints

def greet(name: str) -> str:
    return f"Hello, {name}"


def add(a: int, b: int) -> int:
    return a + b


print(greet("Alice"))
print(add(2, 3))
Hello, Alice
5
The line def add(a: int, b: int) -> int: the hints after the colons say what goes in, the hint after the arrow says what comes out def add(a: int, b: int) -> int: parameter hints: what goes in return hint: what comes out
Read one line and you know the deal, without looking at the body.

name: str is a parameter hint: name should be a string. The arrow and str at the end is the return hint: greet gives back a string. add says two whole numbers go in and a whole number comes out.

A function that returns nothing

def log(message: str) -> None:
    print("LOG:", message)


result = log("saved")
print(result)
LOG: saved
None

log only prints; there's no return, so the function hands back None. -> None tells the reader you call this function for what it does, not for what it gives back.

Hints with default values

def repeat(text: str, times: int = 2) -> str:
    return text * times


print(repeat("ha"))
print(repeat("ha", 3))
haha
hahaha

The order is name, colon and type, then the default. With a hint, put spaces around the =.

A value or None

USERS = {1: "Alice", 2: "Bob"}


def find_user(user_id: int) -> str | None:
    return USERS.get(user_id)


for uid in (1, 7):
    user = find_user(uid)
    if user is None:
        print(uid, "-> not found")
    else:
        print(uid, "->", user)
1 -> Alice
7 -> not found

Sometimes a function can't promise a value. If the ID is in the dict you get a name; if not, get gives back None. So the return hint is str | None, where the bar means "or". The hint warns whoever calls the function to check for None before using the value. In older code you'll see Optional[str], which means the same thing.

What's inside a list or a dict

def shout_all(names: list[str]) -> list[str]:
    return [n.upper() for n in names]


def total(scores: dict[str, int]) -> int:
    return sum(scores.values())


print(shout_all(["ann", "bob"]))
print(total({"maths": 80, "art": 95}))
['ANN', 'BOB']
175

A hint that only says list leaves a question: a list of what? Put the type in square brackets. For a dict, name two types, keys first and then values: dict[str, int] means string keys and whole-number values. (The one-line list inside shout_all is a comprehension.)

Python doesn't check hints

def add(a: int, b: int) -> int:
    return a + b


print(add(2, 3))
print(add("2", "3"))
5
23

Here's the part that surprises people. Passing two strings is exactly what the hints say not to do, and Python doesn't stop you. The plus sign is happy to join two strings, so it prints 23 and finishes without any error. Hints aren't enforced when your code runs, just like the label on that jar.

When a wrong type does fail

def add(a: int, b: int) -> int:
    return a + b


print(add("2", 3))
Traceback (most recent call last):
  File "S02L01_1_TypeHints\wrong_type_fails.py", line 5, in <module>
    print(add("2", 3))
          ~~~^^^^^^^^
  File "S02L01_1_TypeHints\wrong_type_fails.py", line 2, in add
    return a + b
           ~~^~~
TypeError: can only concatenate str (not "int") to str

The values go straight past the hints and reach a + b. The error points at the plus sign on line 2 and says nothing about the hint. When a wrong type fails, it's the operation that fails.

Python keeps the hints

import inspect


def greet(name: str, times: int = 1) -> str:
    return ("Hi " + name + " ") * times


print(greet.__annotations__)
print(inspect.signature(greet))
{'name': <class 'str'>, 'times': <class 'int'>, 'return': <class 'str'>}
(name: str, times: int = 1) -> str

Python doesn't check the hints, but it does keep them. __annotations__ is a dictionary, with the return hint under its own key, return. inspect.signature gives back the whole first line, default included. So other code can ask for the hints.

Who reads the hints

  • Your editor. PyCharm reads the file without running it. On add("2", "3") it marks the string and says it expected an int and got a str, before you run anything. And because it knows name is a string, typing name. offers you string methods.
  • AI tools. Hints tell them what each function takes and gives back. You can prompt one to add type hints, and then the first line of each function is the first thing to check.
  • Libraries. Pydantic and FastAPI build on these same hints; see FastAPI hello world for where they show up.

Quick recap

You writeIt means
name: strthis parameter should be a string
-> intthe function returns an int
-> Nonecalled for what it does, returns nothing
times: int = 2hint first, then default
str | Nonea string, or nothing; check before use
list[str], dict[str, int]what's inside the container

And Python doesn't check any of it when your code runs.

Try it yourself

def average(numbers):
    return sum(numbers) / len(numbers)


print(average([4, 8, 6]))

Add hints to average. It should still print 6.0.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 13 of 48

Previous
Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
Next post
Python lambda, map, filter, Modules and Packages (with pip and venv)

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs

A function is a recipe: write it once, hand in ingredients, get a dish back. input and import, def and return, defaults, returning a tuple, functions as objects, the LEGB scope rule, global and nonlocal, then *args and **kwargs, with real output.

Python lambda, map, filter, Modules and Packages (with pip and venv)

A lambda is a sticky note next to a def recipe card. Sort words and students with key, map as a conveyor belt, filter as a gate, then your own package with __init__.py, two import errors, and pip install into an activated .venv.

Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package

Three work-style use cases (an HR bonus calculator, a product discount pipeline, and a mathkit package) turned into requirement lists and prompts, with one possible result for each read against the list, including the empty-input crash the list forgot.

On this page

  • Parameter hints and return hints
  • A function that returns nothing
  • Hints with default values
  • A value or None
  • What's inside a list or a dict
  • Python doesn't check hints
  • When a wrong type does fail
  • Python keeps the hints
  • Who reads the hints
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.