Python provides 71+ built-in functions that are always available without importing any module. This guide covers all major built-in functions with detailed explanations, syntax, parameters, and examples.
Table of Contents
- Mathematical Functions
- Type Conversion Functions
- Iteration & Sequence Functions
- Object & Attribute Functions
- I/O Functions
- String & Representation Functions
- Compilation & Execution Functions
- Class & OOP Functions
- Utility Functions
- Python Built-in Exceptions & Errors
Mathematical Functions
abs(x)
Returns the absolute value of a number.
Parameters:
x: A number (int, float, or complex)
Returns: Absolute value (magnitude for complex numbers)
Examples:
abs(-5) # 5
abs(-3.14) # 3.14
abs(3+4j) # 5.0 (magnitude: sqrt(3²+4²))
abs(-0) # 0Pythondivmod(a, b)
Returns a tuple containing the quotient and remainder when dividing a by b.
Parameters:
a: Dividend (number)b: Divisor (number)
Returns: Tuple (quotient, remainder) equivalent to (a // b, a % b)
Examples:
divmod(10, 3) # (3, 1)
divmod(9, 4) # (2, 1)
divmod(20, 6) # (3, 2)
divmod(7.5, 2) # (3.0, 1.5)Pythonpow(base, exp[, mod])
Returns base raised to the power of exp. With three arguments, returns (base ** exp) % mod.
Parameters:
base: Base numberexp: Exponentmod: (Optional) Modulus for result
Returns: Computed power value
Examples:
pow(2, 3) # 8 (2³)
pow(5, 2) # 25 (5²)
pow(2, 10, 100) # 24 ((2¹⁰) % 100)
pow(3, -2) # 0.1111... (1/9)Pythonround(number[, ndigits])
Rounds a number to a given precision.
Parameters:
number: Number to roundndigits: (Optional) Number of decimal places (default: 0)
Returns: Rounded number
Examples:
round(3.14159) # 3
round(3.14159, 2) # 3.14
round(2.675, 2) # 2.67 (banker's rounding)
round(1234, -2) # 1200 (round to hundreds)Pythonsum(iterable[, start])
Sums all items in an iterable.
Parameters:
iterable: Sequence of numbersstart: (Optional) Starting value (default: 0)
Returns: Sum of all elements
Examples:
sum([1, 2, 3, 4]) # 10
sum((5, 10, 15), 100) # 130
sum(range(1, 11)) # 55
sum([0.1, 0.2, 0.3]) # 0.6000000000000001Pythonmax(iterable, *[, key, default]) / max(arg1, arg2, *args[, key])
Returns the largest item.
Parameters:
iterable: Sequence to check OR multiple argumentskey: (Optional) Function to extract comparison keydefault: (Optional) Default value if iterable is empty
Returns: Maximum value
Examples:
max([1, 5, 3, 9, 2]) # 9
max(4, 7, 2, 9, 1) # 9
max(['apple', 'zoo', 'bat']) # 'zoo'
max([1, -5, 3], key=abs) # -5 (largest absolute value)
max([], default=0) # 0Pythonmin(iterable, *[, key, default]) / min(arg1, arg2, *args[, key])
Returns the smallest item.
Parameters:
iterable: Sequence to check OR multiple argumentskey: (Optional) Function to extract comparison keydefault: (Optional) Default value if iterable is empty
Returns: Minimum value
Examples:
min([1, 5, 3, 9, 2]) # 1
min(4, 7, 2, 9, 1) # 1
min(['apple', 'zoo', 'bat']) # 'apple'
min([1, -5, 3], key=abs) # 1 (smallest absolute value)
min([], default=0) # 0PythonType Conversion Functions
int([x[, base]])
Converts a value to an integer.
Parameters:
x: Value to convert (string, number, or object with__int__())base: (Optional) Number base for string conversion (2-36)
Returns: Integer value
Examples:
int(3.14) # 3
int('42') # 42
int('1010', 2) # 10 (binary to decimal)
int('FF', 16) # 255 (hex to decimal)
int() # 0Pythonfloat([x])
Converts a value to a floating-point number.
Parameters:
x: Value to convert (string or number)
Returns: Float value
Examples:
float(42) # 42.0
float('3.14') # 3.14
float('inf') # inf
float('-infinity') # -inf
float() # 0.0Pythoncomplex([real[, imag]])
Creates a complex number.
Parameters:
real: Real part (or string representation)imag: (Optional) Imaginary part
Returns: Complex number
Examples:
complex(3, 4) # (3+4j)
complex(2.5) # (2.5+0j)
complex('3+4j') # (3+4j)
complex() # 0jPythonbool([x])
Converts a value to a Boolean.
Parameters:
x: Value to convert
Returns: True or False
Examples:
bool(1) # True
bool(0) # False
bool([]) # False
bool([1, 2]) # True
bool('') # False
bool('hello') # TruePythonstr([object[, encoding[, errors]]])
Converts an object to a string.
Parameters:
object: Object to convertencoding: (Optional) Encoding for byteserrors: (Optional) Error handling strategy
Returns: String representation
Examples:
str(42) # '42'
str([1, 2, 3]) # '[1, 2, 3]'
str(b'hello', 'utf-8') # 'hello'
str(b'\xff', 'utf-8', 'ignore') # ''Pythonbytes([source[, encoding[, errors]]])
Creates an immutable bytes object.
Parameters:
source: Integer (size), iterable, string (with encoding), or bytes-likeencoding: (Optional) Encoding for stringerrors: (Optional) Error handling
Returns: Bytes object
Examples:
bytes(5) # b'\x00\x00\x00\x00\x00'
bytes([65, 66, 67]) # b'ABC'
bytes('hello', 'utf-8') # b'hello'
bytes.fromhex('48656c6c6f') # b'Hello'Pythonbytearray([source[, encoding[, errors]]])
Creates a mutable bytearray object.
Parameters:
- Same as
bytes()
Returns: Mutable bytearray object
Examples:
ba = bytearray(5) # bytearray(b'\x00\x00\x00\x00\x00')
ba = bytearray([65, 66]) # bytearray(b'AB')
ba[0] = 90 # bytearray(b'ZB') - mutable!Pythonlist([iterable])
Creates a list from an iterable.
Parameters:
iterable: (Optional) Any iterable object
Returns: New list
Examples:
list() # []
list('abc') # ['a', 'b', 'c']
list((1, 2, 3)) # [1, 2, 3]
list(range(5)) # [0, 1, 2, 3, 4]Pythontuple([iterable])
Creates a tuple from an iterable.
Parameters:
iterable: (Optional) Any iterable object
Returns: New tuple (immutable)
Examples:
tuple() # ()
tuple([1, 2, 3]) # (1, 2, 3)
tuple('abc') # ('a', 'b', 'c')
tuple(range(3)) # (0, 1, 2)Pythonset([iterable])
Creates a set from an iterable.
Parameters:
iterable: (Optional) Any iterable object
Returns: New set (unordered, unique elements)
Examples:
set() # set()
set([1, 2, 2, 3]) # {1, 2, 3}
set('hello') # {'h', 'e', 'l', 'o'}
set(range(5)) # {0, 1, 2, 3, 4}Pythonfrozenset([iterable])
Creates an immutable set.
Parameters:
iterable: (Optional) Any iterable object
Returns: Immutable frozenset
Examples:
frozenset([1, 2, 3]) # frozenset({1, 2, 3})
frozenset('abc') # frozenset({'a', 'b', 'c'})
# Can be used as dict keys or set elements
d = {frozenset([1, 2]): 'value'}Pythondict([mapping, **kwargs])
Creates a dictionary.
Parameters:
mapping: (Optional) Mapping object or iterable of key-value pairs**kwargs: Keyword arguments become key-value pairs
Returns: New dictionary
Examples:
dict() # {}
dict(a=1, b=2) # {'a': 1, 'b': 2}
dict([('x', 1), ('y', 2)]) # {'x': 1, 'y': 2}
dict(zip(['a', 'b'], [1, 2])) # {'a': 1, 'b': 2}Pythonmemoryview(object)
Creates a memory view object that exposes the buffer interface.
Parameters:
object: Object supporting buffer protocol (bytes, bytearray, etc.)
Returns: Memory view object
Examples:
ba = bytearray(b'hello')
mv = memoryview(ba)
mv[0] # 104 (ASCII 'h')
mv[0:2].tobytes() # b'he'PythonIteration & Sequence Functions
range([start,] stop[, step])
Creates an immutable sequence of numbers.
Parameters:
start: (Optional) Starting number (default: 0)stop: Ending number (exclusive)step: (Optional) Increment (default: 1)
Returns: Range object (iterable)
Examples:
list(range(5)) # [0, 1, 2, 3, 4]
list(range(2, 8)) # [2, 3, 4, 5, 6, 7]
list(range(0, 10, 2)) # [0, 2, 4, 6, 8]
list(range(10, 0, -2)) # [10, 8, 6, 4, 2]Pythonenumerate(iterable[, start])
Returns an enumerate object yielding (index, value) pairs.
Parameters:
iterable: Any iterable objectstart: (Optional) Starting index (default: 0)
Returns: Enumerate object
Examples:
list(enumerate(['a', 'b', 'c'])) # [(0, 'a'), (1, 'b'), (2, 'c')]
list(enumerate('xyz', start=1)) # [(1, 'x'), (2, 'y'), (3, 'z')]
for i, value in enumerate(['apple', 'banana']):
print(f"{i}: {value}")
# 0: apple
# 1: bananaPythonzip(*iterables[, strict])
Aggregates elements from multiple iterables.
Parameters:
*iterables: One or more iterablesstrict: (Python 3.10+) If True, raises error if lengths differ
Returns: Zip object yielding tuples
Examples:
list(zip([1, 2, 3], ['a', 'b', 'c'])) # [(1, 'a'), (2, 'b'), (3, 'c')]
list(zip([1, 2], [10, 20], [100, 200])) # [(1, 10, 100), (2, 20, 200)]
list(zip([1, 2, 3], ['a', 'b'])) # [(1, 'a'), (2, 'b')] - stops at shortest
# Unzipping
pairs = [(1, 'a'), (2, 'b')]
nums, letters = zip(*pairs) # (1, 2), ('a', 'b')Pythonmap(function, iterable, *iterables)
Applies a function to every item of an iterable.
Parameters:
function: Function to applyiterable: One or more iterables
Returns: Map object (iterator)
Examples:
list(map(str.upper, ['hello', 'world'])) # ['HELLO', 'WORLD']
list(map(lambda x: x**2, [1, 2, 3, 4])) # [1, 4, 9, 16]
list(map(pow, [2, 3, 4], [3, 2, 1])) # [8, 9, 4] - pow(2,3), pow(3,2), pow(4,1)Pythonfilter(function, iterable)
Filters items in an iterable based on a function.
Parameters:
function: Function returning True/False (or None to filter falsy values)iterable: Iterable to filter
Returns: Filter object (iterator)
Examples:
list(filter(lambda x: x > 0, [-2, -1, 0, 1, 2])) # [1, 2]
list(filter(str.isdigit, ['1', 'a', '2', 'b'])) # ['1', '2']
list(filter(None, [0, 1, False, True, '', 'hi'])) # [1, True, 'hi']Pythonsorted(iterable[, key][, reverse])
Returns a sorted list from an iterable.
Parameters:
iterable: Iterable to sortkey: (Optional) Function for extracting comparison keyreverse: (Optional) Sort in descending order (default: False)
Returns: New sorted list
Examples:
sorted([3, 1, 4, 1, 5]) # [1, 1, 3, 4, 5]
sorted(['banana', 'apple', 'cherry']) # ['apple', 'banana', 'cherry']
sorted([3, -1, -4, 2], key=abs) # [-1, 2, 3, -4]
sorted(['a', 'BB', 'ccc'], key=len) # ['a', 'BB', 'ccc']
sorted([1, 2, 3], reverse=True) # [3, 2, 1]Pythonreversed(seq)
Returns a reverse iterator.
Parameters:
seq: Sequence to reverse (must have__reversed__()or support indexing)
Returns: Reverse iterator
Examples:
list(reversed([1, 2, 3, 4])) # [4, 3, 2, 1]
list(reversed('hello')) # ['o', 'l', 'l', 'e', 'h']
''.join(reversed('hello')) # 'olleh'Pythoniter(object[, sentinel])
Returns an iterator object.
Parameters:
object: Iterable object or callablesentinel: (Optional) Value to stop iteration when returned by callable
Returns: Iterator object
Examples:
it = iter([1, 2, 3])
next(it) # 1
next(it) # 2
# With sentinel
with open('data.txt') as f:
for line in iter(f.readline, ''): # Read until empty string
print(line)Pythonnext(iterator[, default])
Retrieves the next item from an iterator.
Parameters:
iterator: Iterator objectdefault: (Optional) Value to return if iterator is exhausted
Returns: Next item or default
Examples:
it = iter([1, 2, 3])
next(it) # 1
next(it) # 2
next(it) # 3
next(it, 'Done') # 'Done'
next(it) # Raises StopIterationPythonaiter(async_iterable)
Returns an asynchronous iterator.
Parameters:
async_iterable: Asynchronous iterable object
Returns: Async iterator
Examples:
async def main():
async_iter = aiter(async_range(3))
print(await anext(async_iter)) # 0Pythonanext(async_iterator[, default])
Retrieves the next item from an async iterator.
Parameters:
async_iterator: Async iterator objectdefault: (Optional) Value to return if exhausted
Returns: Awaitable for next item
Examples:
async def main():
async_iter = aiter(async_range(3))
value = await anext(async_iter) # Gets next value
value = await anext(async_iter, None) # With defaultPythonlen(s)
Returns the length of an object.
Parameters:
s: Sequence or collection (must have__len__())
Returns: Integer length
Examples:
len([1, 2, 3]) # 3
len('hello') # 5
len({'a': 1, 'b': 2}) # 2
len(range(10)) # 10Pythonslice([start,] stop[, step])
Creates a slice object for slicing sequences.
Parameters:
start: (Optional) Starting indexstop: Ending indexstep: (Optional) Step value
Returns: Slice object
Examples:
s = slice(1, 5)
[0, 1, 2, 3, 4, 5][s] # [1, 2, 3, 4]
s = slice(0, 10, 2)
list(range(20))[s] # [0, 2, 4, 6, 8]Pythonall(iterable)
Returns True if all elements are truthy (or iterable is empty).
Parameters:
iterable: Iterable to check
Returns: Boolean
Examples:
all([True, True, True]) # True
all([True, False, True]) # False
all([1, 2, 3]) # True
all([1, 0, 3]) # False
all([]) # True (vacuous truth)Pythonany(iterable)
Returns True if any element is truthy.
Parameters:
iterable: Iterable to check
Returns: Boolean
Examples:
any([False, False, True]) # True
any([False, False, False]) # False
any([0, 0, 1]) # True
any([]) # FalsePythonObject & Attribute Functions
object()
Returns a new featureless object (base of all classes).
Parameters: None
Returns: Base object instance
Examples:
obj = object()
isinstance(obj, object) # True
# Useful as a unique sentinel value
MISSING = object()Pythontype(object) / type(name, bases, dict)
Returns the type of an object or creates a new type.
Parameters:
- One argument: Returns type of object
- Three arguments: Creates a new class
name: Class namebases: Tuple of base classesdict: Dictionary of class attributes
Returns: Type object
Examples:
type(42) # <class 'int'>
type('hello') # <class 'str'>
type([1, 2, 3]) # <class 'list'>
# Dynamic class creation
MyClass = type('MyClass', (), {'x': 10})
obj = MyClass()
obj.x # 10Pythonisinstance(object, classinfo)
Checks if an object is an instance of a class.
Parameters:
object: Object to checkclassinfo: Class or tuple of classes
Returns: Boolean
Examples:
isinstance(42, int) # True
isinstance('hello', str) # True
isinstance([1, 2], (list, tuple)) # True
isinstance(3.14, (int, float)) # True
isinstance(True, bool) # TruePythonissubclass(class, classinfo)
Checks if a class is a subclass of another.
Parameters:
class: Class to checkclassinfo: Class or tuple of classes
Returns: Boolean
Examples:
issubclass(bool, int) # True
issubclass(list, object) # True
issubclass(str, (list, str)) # True
issubclass(int, str) # FalsePythonid(object)
Returns the unique identifier of an object.
Parameters:
object: Any object
Returns: Integer (memory address in CPython)
Examples:
a = [1, 2, 3]
b = a
id(a) == id(b) # True (same object)
c = [1, 2, 3]
id(a) == id(c) # False (different objects)Pythonhash(object)
Returns the hash value of an object.
Parameters:
object: Hashable object
Returns: Integer hash value
Examples:
hash(42) # 42
hash('hello') # Variable (but consistent in session)
hash((1, 2, 3)) # Tuples are hashable
hash([1, 2, 3]) # TypeError: unhashable type: 'list'Pythoncallable(object)
Checks if an object appears callable.
Parameters:
object: Object to check
Returns: Boolean
Examples:
callable(print) # True
callable(lambda x: x) # True
callable(42) # False
callable(str) # True (class constructor)Pythongetattr(object, name[, default])
Gets the value of an object’s attribute.
Parameters:
object: Object to inspectname: Attribute name (string)default: (Optional) Default value if attribute doesn’t exist
Returns: Attribute value
Examples:
class Person:
name = "Alice"
p = Person()
getattr(p, 'name') # 'Alice'
getattr(p, 'age', 25) # 25 (default)
getattr(p, 'missing') # AttributeErrorPythonsetattr(object, name, value)
Sets the value of an object’s attribute.
Parameters:
object: Object to modifyname: Attribute name (string)value: Value to set
Returns: None
Examples:
class Person:
pass
p = Person()
setattr(p, 'name', 'Bob')
p.name # 'Bob'
setattr(p, 'age', 30)
p.age # 30Pythondelattr(object, name)
Deletes an attribute from an object.
Parameters:
object: Object to modifyname: Attribute name (string)
Returns: None
Examples:
class Person:
name = "Alice"
p = Person()
delattr(p, 'name') # Deletes instance attribute
hasattr(p, 'name') # True if class attribute existsPythonhasattr(object, name)
Checks if an object has a specific attribute.
Parameters:
object: Object to checkname: Attribute name (string)
Returns: Boolean
Examples:
class Person:
name = "Alice"
p = Person()
hasattr(p, 'name') # True
hasattr(p, 'age') # False
hasattr([], 'append') # TruePythondir([object])
Returns a list of attributes and methods of an object.
Parameters:
object: (Optional) Object to inspect (defaults to current scope)
Returns: List of strings (attribute names)
Examples:
dir() # Local namespace
dir([]) # ['append', 'clear', 'copy', ...]
dir(str) # ['capitalize', 'center', ...]
class MyClass:
x = 10
dir(MyClass) # [..., 'x']Pythonvars([object])
Returns the __dict__ attribute of an object.
Parameters:
object: (Optional) Object with__dict__(defaults to locals())
Returns: Dictionary of attributes
Examples:
class Person:
def __init__(self, name):
self.name = name
p = Person("Alice")
vars(p) # {'name': 'Alice'}
vars() # Same as locals()Pythonglobals()
Returns a dictionary of the current global symbol table.
Parameters: None
Returns: Dictionary of global variables
Examples:
x = 10
y = 20
globals()['x'] # 10
globals()['y'] # 20
# Can modify globals
globals()['z'] = 30
print(z) # 30Pythonlocals()
Returns a dictionary of the current local symbol table.
Parameters: None
Returns: Dictionary of local variables
Examples:
def my_func():
a = 1
b = 2
print(locals()) # {'a': 1, 'b': 2}
my_func()
# At module level, locals() == globals()PythonI/O Functions
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Prints objects to a text stream.
Parameters:
*objects: Objects to printsep: Separator between objects (default: space)end: String appended at end (default: newline)file: Output stream (default: stdout)flush: Force flush buffer (default: False)
Returns: None
Examples:
print('Hello', 'World') # Hello World
print('A', 'B', 'C', sep='-') # A-B-C
print('Loading...', end=' ') # Loading... (no newline)
print('Done') # Done
# Print to file
with open('log.txt', 'w') as f:
print('Log entry', file=f)Pythoninput([prompt])
Reads a line from input (stdin).
Parameters:
prompt: (Optional) String to display before reading
Returns: String (user input without trailing newline)
Examples:
name = input('Enter your name: ')
# User types: Alice
# name = 'Alice'
age = int(input('Enter age: '))
# User types: 25
# age = 25Pythonopen(file, mode='r', ...)
Opens a file and returns a file object.
Parameters:
file: File path (string or path-like)mode: Opening mode (default: ‘r’)'r': Read (default)'w': Write (truncate)'a': Append'b': Binary mode'+': Read and write
- Additional parameters:
encoding,errors,buffering, etc.
Returns: File object
Examples:
# Reading
with open('file.txt', 'r') as f:
content = f.read()
# Writing
with open('output.txt', 'w', encoding='utf-8') as f:
f.write('Hello, World!')
# Binary mode
with open('image.png', 'rb') as f:
data = f.read()
# Appending
with open('log.txt', 'a') as f:
f.write('New log entry\n')PythonString & Representation Functions
chr(i)
Returns the Unicode character for a code point.
Parameters:
i: Integer code point (0 to 1,114,111)
Returns: Single-character string
Examples:
chr(65) # 'A'
chr(97) # 'a'
chr(8364) # '€'
chr(128512) # '😀'Pythonord(c)
Returns the Unicode code point of a character.
Parameters:
c: Single character string
Returns: Integer code point
Examples:
ord('A') # 65
ord('a') # 97
ord('€') # 8364
ord('😀') # 128512Pythonascii(object)
Returns a string with ASCII-only representation of an object.
Parameters:
object: Any object
Returns: String (non-ASCII chars escaped)
Examples:
ascii('hello') # "'hello'"
ascii('café') # "'caf\\xe9'"
ascii('😀') # "'\\U0001f600'"
ascii([1, 2, 3]) # '[1, 2, 3]'Pythonrepr(object)
Returns a string representation suitable for debugging.
Parameters:
object: Any object
Returns: String (official representation)
Examples:
repr('hello') # "'hello'"
repr(42) # '42'
repr([1, 2, 3]) # '[1, 2, 3]'
class Person:
def __repr__(self):
return 'Person()'
repr(Person()) # 'Person()'Pythonformat(value[, format_spec])
Formats a value using a format specification.
Parameters:
value: Value to formatformat_spec: (Optional) Format specification string
Returns: Formatted string
Examples:
format(42, 'd') # '42' (decimal)
format(42, 'b') # '101010' (binary)
format(42, 'x') # '2a' (hexadecimal)
format(3.14159, '.2f') # '3.14'
format(1234, ',') # '1,234'
format(0.5, '%') # '50.000000%'Pythonbin(x)
Converts an integer to a binary string.
Parameters:
x: Integer
Returns: Binary string with ‘0b’ prefix
Examples:
bin(10) # '0b1010'
bin(255) # '0b11111111'
bin(-5) # '-0b101'
bin(0) # '0b0'Pythonoct(x)
Converts an integer to an octal string.
Parameters:
x: Integer
Returns: Octal string with ‘0o’ prefix
Examples:
oct(8) # '0o10'
oct(64) # '0o100'
oct(255) # '0o377'Pythonhex(x)
Converts an integer to a hexadecimal string.
Parameters:
x: Integer
Returns: Hexadecimal string with ‘0x’ prefix
Examples:
hex(15) # '0xf'
hex(255) # '0xff'
hex(4096) # '0x1000'
hex(-16) # '-0x10'PythonCompilation & Execution Functions
eval(expression[, globals[, locals]])
Evaluates a Python expression string.
Parameters:
expression: String or code objectglobals: (Optional) Global namespacelocals: (Optional) Local namespace
Returns: Result of expression
Examples:
eval('2 + 3') # 5
eval('[x**2 for x in range(5)]') # [0, 1, 4, 9, 16]
x = 10
eval('x * 2') # 20
# With custom namespace
eval('a + b', {'a': 5, 'b': 3}) # 8Python⚠️ Security Warning: Never use eval() on untrusted input!
exec(object[, globals[, locals]])
Executes Python code dynamically.
Parameters:
object: String, bytes, or code objectglobals: (Optional) Global namespacelocals: (Optional) Local namespace
Returns: None (modifies namespaces in place)
Examples:
exec('x = 5')
print(x) # 5
code = '''
def greet(name):
return f"Hello, {name}"
'''
exec(code)
print(greet('Alice')) # Hello, Alice
# With custom namespace
namespace = {}
exec('result = 2 + 2', namespace)
print(namespace['result']) # 4Python⚠️ Security Warning: Never use exec() on untrusted input!
compile(source, filename, mode[, flags[, dont_inherit[, optimize]]])
Compiles source code into a code object.
Parameters:
source: Source code (string, bytes, or AST)filename: Filename (for error messages)mode: Compilation mode:'exec': For modules/statements'eval': For expressions'single': For interactive statements
Returns: Code object
Examples:
# Compile and execute
code = compile('print("Hello")', '<string>', 'exec')
exec(code) # Hello
# Compile expression
expr = compile('2 + 3', '<string>', 'eval')
eval(expr) # 5
# Pre-compile for performance
code = compile('x**2', '<string>', 'eval')
for x in range(5):
print(eval(code)) # 0, 1, 4, 9, 16Pythonhelp([object])
Invokes the built-in help system.
Parameters:
object: (Optional) Object to get help for
Returns: None (prints documentation)
Examples:
help() # Interactive help
help(print) # Help for print function
help(str) # Help for str class
help(str.upper) # Help for str.upper methodPythonClass & OOP Functions
classmethod(function)
Transforms a method into a class method (decorator).
Parameters:
function: Method to transform
Returns: Class method object
Examples:
class MyClass:
count = 0
@classmethod
def increment(cls):
cls.count += 1
@classmethod
def create_default(cls):
return cls()
MyClass.increment()
print(MyClass.count) # 1Pythonstaticmethod(function)
Transforms a method into a static method (decorator).
Parameters:
function: Method to transform
Returns: Static method object
Examples:
class MathUtils:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def multiply(a, b):
return a * b
MathUtils.add(5, 3) # 8 (no instance needed)Pythonproperty(fget=None, fset=None, fdel=None, doc=None)
Creates a property attribute (decorator).
Parameters:
fget: Getter functionfset: Setter functionfdel: Deleter functiondoc: Docstring
Returns: Property object
Examples:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius must be positive")
self._radius = value
@property
def area(self):
return 3.14159 * self._radius ** 2
c = Circle(5)
print(c.radius) # 5
print(c.area) # 78.53975
c.radius = 10 # Uses setterPythonsuper([type[, object-or-type]])
Returns a proxy object for accessing parent class methods.
Parameters:
type: (Optional) Class typeobject-or-type: (Optional) Object or type
Returns: Super object (proxy)
Examples:
class Parent:
def greet(self):
return "Hello from Parent"
class Child(Parent):
def greet(self):
parent_msg = super().greet()
return f"{parent_msg} and Child"
c = Child()
c.greet() # "Hello from Parent and Child"
# Multiple inheritance
class A:
def method(self):
return "A"
class B:
def method(self):
return "B"
class C(A, B):
def method(self):
return super().method() + " -> C"
C().method() # "A -> C"PythonUtility Functions
breakpoint(*args, **kwargs)
Enters the debugger at the call site (Python 3.7+).
Parameters:
*args,**kwargs: Passed to debugger
Returns: None
Examples:
def complex_function(x):
y = x * 2
breakpoint() # Debugger starts here
z = y + 10
return z
complex_function(5) # Interactive debugging sessionPythoncopyright, credits, license
Display copyright, credits, or license information.
Parameters: None (callable objects)
Returns: None (prints information)
Examples:
copyright # Copyright info
credits # Credits
license # License textPythonexit([code]) / quit([code])
Exits the interpreter.
Parameters:
code: (Optional) Exit code (default: 0)
Returns: Never returns (raises SystemExit)
Examples:
exit() # Exit with code 0
exit(1) # Exit with code 1 (error)
quit() # Same as exit()PythonBest Practices & Tips
Performance Considerations
- Use built-ins when possible – They’re implemented in C and optimized
map()vs list comprehension – List comprehensions are often clearerfilter()vs list comprehension – Comprehensions withifare more Pythonic- Pre-compile with
compile()– For repeated evaluation of same code
Common Patterns
Converting types:
# String to list of chars
list('hello') # ['h', 'e', 'l', 'l', 'o']
# Range to list
list(range(5)) # [0, 1, 2, 3, 4]
# Dictionary from two lists
dict(zip(keys, values))PythonFiltering and transformation:
# Filter and transform
[x**2 for x in range(10) if x % 2 == 0]
# Using map and filter
list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, range(10))))PythonWorking with iterators:
# Efficient iteration
for i, item in enumerate(items, start=1):
print(f"{i}. {item}")
# Parallel iteration
for name, age in zip(names, ages):
print(f"{name}: {age}")PythonSafety Notes
Dangerous functions (avoid with untrusted input):
eval()– Can execute arbitrary codeexec()– Can execute arbitrary codecompile()– Can create malicious code objectsopen()– Can access filesystem__import__()– Can import arbitrary modules
Type checking:
# Prefer isinstance over type
isinstance(x, int) # ✓ Good (works with subclasses)
type(x) == int # ✗ Less flexible
# Check multiple types
isinstance(x, (int, float))PythonQuick Reference Table
| Category | Functions |
|---|---|
| Math | abs, divmod, max, min, pow, round, sum |
| Type Conversion | bool, int, float, complex, str, bytes, bytearray, list, tuple, set, frozenset, dict |
| Iteration | range, enumerate, zip, map, filter, sorted, reversed, iter, next, len, all, any |
| Async | aiter, anext |
| Object/Attributes | object, type, isinstance, issubclass, id, hash, callable, getattr, setattr, delattr, hasattr, dir, vars, globals, locals |
| I/O | print, input, open |
| String/Repr | chr, ord, ascii, repr, format, bin, oct, hex |
| Execution | eval, exec, compile |
| OOP | classmethod, staticmethod, property, super |
| Utility | help, breakpoint, memoryview, slice |
| Interactive | copyright, credits, license, exit, quit |
Conclusion
Python’s built-in functions provide a powerful toolkit for common programming tasks without requiring imports. Mastering these functions enables you to write more concise, readable, and efficient code. Remember:
- Built-ins are optimized and should be preferred over custom implementations
- Many built-ins work seamlessly with iterators for memory efficiency
- Type conversion functions are essential for data processing
- OOP functions enable advanced class design patterns
- Always validate and sanitize input before using
eval()orexec()
For detailed documentation on any function, use help(function_name) in your Python interpreter.
Python Built-in Exceptions & Errors
Python provides a rich hierarchy of built-in exceptions for error handling. Understanding these exceptions is crucial for writing robust, error-resistant code.
Exception Hierarchy
BaseException
├── BaseExceptionGroup
├── GeneratorExit
├── KeyboardInterrupt
├── SystemExit
└── Exception
├── ArithmeticError
│ ├── FloatingPointError
│ ├── OverflowError
│ └── ZeroDivisionError
├── AssertionError
├── AttributeError
├── BufferError
├── EOFError
├── ExceptionGroup
├── ImportError
│ └── ModuleNotFoundError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── MemoryError
├── NameError
│ └── UnboundLocalError
├── OSError
│ ├── BlockingIOError
│ ├── ChildProcessError
│ ├── ConnectionError
│ │ ├── BrokenPipeError
│ │ ├── ConnectionAbortedError
│ │ ├── ConnectionRefusedError
│ │ └── ConnectionResetError
│ ├── FileExistsError
│ ├── FileNotFoundError
│ ├── InterruptedError
│ ├── IsADirectoryError
│ ├── NotADirectoryError
│ ├── PermissionError
│ ├── ProcessLookupError
│ └── TimeoutError
├── ReferenceError
├── RuntimeError
│ ├── NotImplementedError
│ └── RecursionError
├── StopIteration
├── StopAsyncIteration
├── SyntaxError
│ └── IndentationError
│ └── TabError
├── SystemError
├── TypeError
├── ValueError
│ └── UnicodeError
│ ├── UnicodeDecodeError
│ ├── UnicodeEncodeError
│ └── UnicodeTranslateError
└── Warning
├── BytesWarning
├── DeprecationWarning
├── EncodingWarning
├── FutureWarning
├── ImportWarning
├── PendingDeprecationWarning
├── ResourceWarning
├── RuntimeWarning
├── SyntaxWarning
├── UnicodeWarning
└── UserWarningBashBase Exceptions
BaseException
The base class for all built-in exceptions. User-defined exceptions should inherit from Exception, not BaseException.
Examples:
try:
raise BaseException("Critical error")
except BaseException as e:
print(f"Caught: {e}")PythonSystemExit
Raised by sys.exit() – used to exit the interpreter.
Attributes:
code: Exit status code
Examples:
import sys
try:
sys.exit(1)
except SystemExit as e:
print(f"Exit code: {e.code}") # Exit code: 1PythonKeyboardInterrupt
Raised when the user hits the interrupt key (Ctrl+C or Delete).
Examples:
try:
while True:
pass # Infinite loop
except KeyboardInterrupt:
print("\nProgram interrupted by user")PythonGeneratorExit
Raised when a generator’s close() method is called.
Examples:
def my_generator():
try:
yield 1
yield 2
except GeneratorExit:
print("Generator is closing")
raise
gen = my_generator()
next(gen)
gen.close() # Triggers GeneratorExitPythonArithmetic Exceptions
ArithmeticError
Base class for arithmetic errors: OverflowError, ZeroDivisionError, FloatingPointError.
ZeroDivisionError
Raised when dividing by zero.
Examples:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
try:
result = 10 % 0
except ZeroDivisionError:
print("Cannot modulo by zero!")PythonOverflowError
Raised when an arithmetic operation exceeds limits.
Examples:
import math
try:
math.exp(1000) # Too large for float
except OverflowError:
print("Number too large!")PythonFloatingPointError
Raised when a floating-point operation fails (rarely used in Python).
Type & Value Exceptions
TypeError
Raised when an operation is applied to an object of inappropriate type.
Common Causes:
- Wrong number of arguments
- Unsupported operand types
- Object not callable
- Object not subscriptable
Examples:
# Wrong type for operation
try:
result = "hello" + 5
except TypeError as e:
print(e) # can only concatenate str (not "int") to str
# Not callable
try:
x = 5
x()
except TypeError as e:
print(e) # 'int' object is not callable
# Wrong number of arguments
try:
print("hello", "world", sep=",", extra="oops")
except TypeError as e:
print(e) # print() got an unexpected keyword argument 'extra'PythonValueError
Raised when an operation receives an argument with the right type but inappropriate value.
Examples:
# Invalid literal for conversion
try:
int("hello")
except ValueError as e:
print(e) # invalid literal for int() with base 10: 'hello'
# Value out of range
try:
import math
math.sqrt(-1) # Use complex numbers instead
except ValueError as e:
print(e) # math domain error
# Invalid value for unpack
try:
a, b = [1, 2, 3]
except ValueError as e:
print(e) # too many values to unpack (expected 2)PythonAssertionError
Raised when an assert statement fails.
Examples:
try:
x = 5
assert x > 10, "x must be greater than 10"
except AssertionError as e:
print(e) # x must be greater than 10
# Enable/disable with -O flag
# python -O script.py # Assertions are ignoredPythonLookup Exceptions
LookupError
Base class for IndexError and KeyError.
IndexError
Raised when trying to access an index that doesn’t exist.
Examples:
my_list = [1, 2, 3]
try:
value = my_list[10]
except IndexError as e:
print(e) # list index out of range
try:
my_list[0:100] # Slicing doesn't raise IndexError
print("Slicing is safe!")
except IndexError:
pass # Won't be raisedPythonKeyError
Raised when a dictionary key is not found.
Examples:
my_dict = {"name": "Alice", "age": 30}
try:
value = my_dict["email"]
except KeyError as e:
print(f"Key {e} not found") # Key 'email' not found
# Safe alternatives
value = my_dict.get("email", "not provided") # Returns defaultPythonAttribute & Name Exceptions
AttributeError
Raised when attribute reference or assignment fails.
Examples:
class Person:
name = "Alice"
p = Person()
try:
print(p.age) # Attribute doesn't exist
except AttributeError as e:
print(e) # 'Person' object has no attribute 'age'
try:
my_list = [1, 2, 3]
my_list.push(4) # Lists don't have push, use append
except AttributeError as e:
print(e) # 'list' object has no attribute 'push'PythonNameError
Raised when a local or global name is not found.
Examples:
try:
print(undefined_variable)
except NameError as e:
print(e) # name 'undefined_variable' is not defined
try:
result = x + 5 # x not defined
except NameError as e:
print(e) # name 'x' is not definedPythonUnboundLocalError
Raised when referencing a local variable before assignment (subclass of NameError).
Examples:
def my_function():
try:
print(x) # Reference before assignment
x = 10
except UnboundLocalError as e:
print(e) # local variable 'x' referenced before assignment
my_function()
# Common mistake with global variables
count = 0
def increment():
try:
count += 1 # UnboundLocalError!
except UnboundLocalError:
print("Need to use 'global count' first")
increment()PythonImport Exceptions
ImportError
Raised when an import statement fails.
Examples:
try:
import nonexistent_module
except ImportError as e:
print(e) # No module named 'nonexistent_module'
try:
from math import nonexistent_function
except ImportError as e:
print(e) # cannot import name 'nonexistent_function'PythonModuleNotFoundError
Raised when a module cannot be located (subclass of ImportError, Python 3.6+).
Examples:
try:
import some_fake_module
except ModuleNotFoundError as e:
print(e) # No module named 'some_fake_module'
print(e.name) # some_fake_modulePythonOS & I/O Exceptions
OSError
Base class for operating system errors. Many specific subclasses exist.
Attributes:
errno: Error numberstrerror: Error messagefilename: Related filename (if applicable)
Examples:
import errno
try:
with open('/nonexistent/file.txt') as f:
content = f.read()
except OSError as e:
print(f"Error {e.errno}: {e.strerror}")
print(f"File: {e.filename}")PythonFileNotFoundError
Raised when a file or directory is requested but doesn’t exist.
Examples:
try:
with open('missing_file.txt', 'r') as f:
content = f.read()
except FileNotFoundError as e:
print(e) # [Errno 2] No such file or directory: 'missing_file.txt'PythonFileExistsError
Raised when trying to create a file that already exists.
Examples:
import os
try:
os.mkdir('existing_directory')
except FileExistsError:
print("Directory already exists!")
# Safe alternative
os.makedirs('path/to/dir', exist_ok=True)PythonPermissionError
Raised when trying to run an operation without adequate permissions.
Examples:
try:
with open('/root/protected_file.txt', 'w') as f:
f.write('data')
except PermissionError as e:
print(e) # [Errno 13] Permission deniedPythonIsADirectoryError
Raised when a file operation is requested on a directory.
Examples:
try:
with open('/home/user/', 'r') as f:
content = f.read()
except IsADirectoryError:
print("Cannot read a directory as a file!")PythonNotADirectoryError
Raised when a directory operation is requested on a non-directory.
Examples:
import os
try:
os.listdir('regular_file.txt')
except NotADirectoryError:
print("Not a directory!")PythonTimeoutError
Raised when a system operation times out.
Examples:
import socket
try:
sock = socket.socket()
sock.settimeout(1)
sock.connect(('192.168.1.999', 80))
except TimeoutError:
print("Connection timed out!")PythonConnection Exceptions
ConnectionError
Base class for connection-related errors.
BrokenPipeError
Raised when trying to write to a pipe with no readers.
ConnectionAbortedError
Raised when a connection attempt is aborted.
ConnectionRefusedError
Raised when a connection attempt is refused.
Examples:
import socket
try:
sock = socket.socket()
sock.connect(('localhost', 9999)) # Nothing listening
except ConnectionRefusedError:
print("Connection refused!")
try:
# Writing to closed socket
sock.send(b'data')
except BrokenPipeError:
print("Broken pipe!")PythonConnectionResetError
Raised when a connection is reset by peer.
Runtime Exceptions
RuntimeError
Raised when an error doesn’t fit other categories.
Examples:
# Dictionary changed during iteration
try:
d = {'a': 1, 'b': 2}
for key in d:
d[key + '_new'] = d[key] # Modifying during iteration
except RuntimeError as e:
print(e) # dictionary changed size during iterationPythonRecursionError
Raised when maximum recursion depth is exceeded (subclass of RuntimeError).
Examples:
import sys
print(sys.getrecursionlimit()) # Default: 1000
def infinite_recursion():
return infinite_recursion()
try:
infinite_recursion()
except RecursionError:
print("Maximum recursion depth exceeded!")
# Increase limit (use with caution)
sys.setrecursionlimit(2000)PythonNotImplementedError
Raised in abstract methods that should be overridden (subclass of RuntimeError).
Examples:
class Animal:
def speak(self):
raise NotImplementedError("Subclasses must implement speak()")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
pass # Forgot to implement speak()
dog = Dog()
dog.speak() # "Woof!"
cat = Cat()
try:
cat.speak()
except NotImplementedError as e:
print(e) # Subclasses must implement speak()PythonSyntax Exceptions
SyntaxError
Raised when the parser encounters a syntax error.
Attributes:
filename: File where error occurredlineno: Line numberoffset: Column offsettext: Line of code
Examples:
# These cause SyntaxError at parse time:
# if True
# print("missing colon")
# def func(
# print("unclosed parenthesis")
try:
eval('x === 5') # Invalid syntax
except SyntaxError as e:
print(f"Syntax error at line {e.lineno}: {e.msg}")PythonIndentationError
Raised when indentation is incorrect (subclass of SyntaxError).
Examples:
# This causes IndentationError:
# def my_func():
# print("wrong indentation")
code = """
if True:
print('bad indent')
"""
try:
exec(code)
except IndentationError as e:
print(e) # expected an indented blockPythonTabError
Raised when tabs and spaces are mixed inconsistently (subclass of IndentationError).
Examples:
# Mix of tabs and spaces (run with python -tt)
code = """
def func():
\tif True:
pass # Tab vs spaces
"""
try:
compile(code, '<string>', 'exec')
except TabError:
print("Inconsistent use of tabs and spaces!")PythonMemory & System Exceptions
MemoryError
Raised when an operation runs out of memory.
Examples:
try:
# Try to create a huge list
huge_list = [0] * (10 ** 100)
except MemoryError:
print("Out of memory!")
try:
# Infinite string concatenation
s = "a"
while True:
s += s
except MemoryError:
print("Memory exhausted!")PythonSystemError
Raised when the interpreter finds an internal error.
Examples:
# Rare - indicates Python bug
# Usually you won't catch this in normal codePythonIterator Exceptions
StopIteration
Raised by next() when there are no more items in an iterator.
Attributes:
value: Value returned by generator
Examples:
it = iter([1, 2, 3])
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3
try:
print(next(it)) # No more items
except StopIteration:
print("Iterator exhausted")
# With default value (no exception)
print(next(it, 'Done')) # 'Done'PythonStopAsyncIteration
Async version of StopIteration (Python 3.5+).
Examples:
async def async_generator():
yield 1
yield 2
async def main():
agen = async_generator()
try:
while True:
value = await agen.__anext__()
print(value)
except StopAsyncIteration:
print("Async iterator exhausted")PythonUnicode Exceptions
UnicodeError
Base class for Unicode-related errors.
UnicodeDecodeError
Raised when a Unicode decoding error occurs.
Examples:
byte_data = b'\xff\xfe'
try:
text = byte_data.decode('utf-8')
except UnicodeDecodeError as e:
print(f"Cannot decode byte {e.object[e.start]} at position {e.start}")
print(f"Codec: {e.encoding}")
print(f"Reason: {e.reason}")
# Handle with error handler
text = byte_data.decode('utf-8', errors='ignore') # Skip bad bytes
text = byte_data.decode('utf-8', errors='replace') # Replace with �PythonUnicodeEncodeError
Raised when a Unicode encoding error occurs.
Examples:
text = "Hello 😀 World"
try:
encoded = text.encode('ascii')
except UnicodeEncodeError as e:
print(f"Cannot encode character '{e.object[e.start]}' at position {e.start}")
# Handle gracefully
encoded = text.encode('ascii', errors='ignore') # Skip
encoded = text.encode('ascii', errors='replace') # Replace with ?
encoded = text.encode('ascii', errors='xmlcharrefreplace') # 😀PythonUnicodeTranslateError
Raised when a Unicode translation error occurs.
Examples:
try:
# Custom translation with errors
text = "hello\uffffworld"
text.translate({0xffff: None}) # Remove character
except UnicodeTranslateError as e:
print(f"Translation error at position {e.start}")PythonBuffer & Reference Exceptions
BufferError
Raised when a buffer-related operation cannot be performed.
Examples:
ba = bytearray(b'hello')
mv = memoryview(ba)
try:
ba.clear() # Can't modify while memoryview exists
except BufferError:
print("Buffer is locked by memoryview!")
mv.release()
ba.clear() # Now it worksPythonReferenceError
Raised when a weak reference proxy is used after the referent has been garbage collected.
Examples:
import weakref
class MyClass:
pass
obj = MyClass()
weak_ref = weakref.ref(obj)
print(weak_ref()) # <__main__.MyClass object at ...>
del obj # Delete the object
try:
print(weak_ref()()) # Object is gone
except TypeError: # weak_ref() returns None
print("Object has been garbage collected")PythonEOFError
Raised when input() hits an end-of-file condition.
Examples:
# When input stream ends (Ctrl+D on Unix, Ctrl+Z on Windows)
try:
name = input("Enter name: ")
except EOFError:
print("\nNo input received (EOF)")
# Reading from file as stdin
# python script.py < input.txtPythonWarning Categories
Warnings are not errors but alerts about potentially problematic code. Use the warnings module to control them.
Warning
Base class for all warnings.
UserWarning
User-generated warnings.
Examples:
import warnings
warnings.warn("This is deprecated", UserWarning)
# Control warnings
warnings.filterwarnings('ignore', category=UserWarning)
warnings.filterwarnings('error', category=UserWarning) # Treat as errorPythonDeprecationWarning
Warnings about deprecated features.
Examples:
import warnings
def old_function():
warnings.warn(
"old_function is deprecated, use new_function instead",
DeprecationWarning,
stacklevel=2
)
pass
# By default, DeprecationWarning is ignored
# Enable with: python -W default script.pyPythonFutureWarning
Warnings about constructs that will change in the future.
SyntaxWarning
Warnings about dubious syntax.
RuntimeWarning
Warnings about dubious runtime behavior.
Examples:
import warnings
import numpy as np
# Division by zero in numpy
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
try:
result = np.array([1, 2, 3]) / 0
except RuntimeWarning:
print("Runtime warning caught!")PythonResourceWarning
Warnings about resource usage (unclosed files, etc.).
Examples:
import warnings
warnings.simplefilter('always', ResourceWarning)
# This will warn about unclosed file
f = open('test.txt', 'w')
# f.close() # Forgot to close
# Better: use context manager
with open('test.txt', 'w') as f:
f.write('data') # Automatically closedPythonOther Warning Types
BytesWarning: Warnings about bytes/bytearray operationsImportWarning: Warnings about import issuesUnicodeWarning: Warnings about Unicode issuesPendingDeprecationWarning: Warnings about future deprecationsEncodingWarning: Warnings about encoding issues (Python 3.10+)
Exception Groups (Python 3.11+)
ExceptionGroup / BaseExceptionGroup
Groups multiple exceptions together.
Examples:
# Python 3.11+
def process_items(items):
errors = []
for item in items:
try:
process(item)
except Exception as e:
errors.append(e)
if errors:
raise ExceptionGroup("Multiple errors occurred", errors)
# Catch with except*
try:
raise ExceptionGroup("group", [
ValueError("bad value"),
TypeError("bad type"),
])
except* ValueError as e:
print(f"Caught ValueError group: {e.exceptions}")
except* TypeError as e:
print(f"Caught TypeError group: {e.exceptions}")PythonCustom Exceptions
Creating custom exceptions for your applications:
Examples:
# Simple custom exception
class CustomError(Exception):
pass
# Exception with additional data
class ValidationError(Exception):
def __init__(self, field, value, message):
self.field = field
self.value = value
super().__init__(message)
try:
raise ValidationError('age', -5, 'Age must be positive')
except ValidationError as e:
print(f"Field '{e.field}' has invalid value: {e.value}")
print(f"Error: {e}")
# Exception hierarchy
class ApplicationError(Exception):
"""Base exception for application"""
pass
class DatabaseError(ApplicationError):
"""Database-related errors"""
pass
class NetworkError(ApplicationError):
"""Network-related errors"""
pass
# Catch all application errors
try:
raise DatabaseError("Connection failed")
except ApplicationError as e:
print(f"Application error: {e}")PythonException Handling Best Practices
1. Be Specific
# Bad - too broad
try:
value = my_dict['key']
except Exception:
pass
# Good - specific
try:
value = my_dict['key']
except KeyError:
value = default_valuePython2. Don’t Silence Exceptions
# Bad - silent failure
try:
risky_operation()
except Exception:
pass
# Good - log or handle
import logging
try:
risky_operation()
except Exception as e:
logging.error(f"Operation failed: {e}")
raise # Re-raise if you can't handlePython3. Use Finally for Cleanup
# Ensure cleanup happens
file = None
try:
file = open('data.txt')
process(file)
except IOError as e:
print(f"Error: {e}")
finally:
if file:
file.close()
# Better: use context manager
with open('data.txt') as file:
process(file) # Automatically cleaned upPython4. Use Else Clause
try:
result = risky_operation()
except ValueError as e:
print(f"Error: {e}")
else:
# Only runs if no exception
print(f"Success: {result}")
finally:
# Always runs
cleanup()Python5. Chain Exceptions
# Python 3.x - preserve original exception
try:
process_data()
except ValueError as e:
raise CustomError("Processing failed") from e
# Suppress original exception (use sparingly)
try:
old_operation()
except OldError as e:
raise NewError("New error") from NonePython6. Use Context Managers
# Automatic resource management
from contextlib import contextmanager
@contextmanager
def managed_resource():
resource = acquire_resource()
try:
yield resource
finally:
release_resource(resource)
with managed_resource() as res:
use(res) # Automatically cleaned upPythonCommon Exception Patterns
Pattern 1: Try-Except-Else-Finally
def read_config(filename):
try:
with open(filename) as f:
config = json.load(f)
except FileNotFoundError:
print(f"Config file {filename} not found")
config = default_config()
except json.JSONDecodeError as e:
print(f"Invalid JSON: {e}")
config = default_config()
else:
print("Config loaded successfully")
validate_config(config)
finally:
print("Config loading completed")
return configPythonPattern 2: Multiple Exception Types
try:
operation()
except (TypeError, ValueError) as e:
handle_input_error(e)
except (IOError, OSError) as e:
handle_io_error(e)
except Exception as e:
handle_unexpected_error(e)
raise # Re-raise unexpected errorsPythonPattern 3: Nested Try-Except
try:
data = fetch_data()
try:
processed = process_data(data)
except ProcessingError:
processed = fallback_process(data)
except NetworkError:
data = cached_data()
processed = process_data(data)PythonPattern 4: Assertion with Custom Message
def divide(a, b):
assert b != 0, f"Cannot divide {a} by zero"
return a / b
# Enable assertions in production with care
# They can be disabled with python -OPythonDebugging Exceptions
Get Exception Information
import sys
import traceback
try:
risky_operation()
except Exception as e:
# Exception type, value, traceback
exc_type, exc_value, exc_traceback = sys.exc_info()
print(f"Type: {exc_type.__name__}")
print(f"Value: {exc_value}")
print(f"Line: {exc_traceback.tb_lineno}")
# Print full traceback
traceback.print_exc()
# Get traceback as string
tb_str = ''.join(traceback.format_tb(exc_traceback))
print(tb_str)PythonException Attributes
try:
raise ValueError("Invalid value")
except ValueError as e:
print(e.args) # ('Invalid value',)
print(str(e)) # Invalid value
print(repr(e)) # ValueError('Invalid value')
print(type(e).__name__) # ValueErrorPythonQuick Reference Table – Exceptions
| Exception | When Raised | Common Causes |
|---|---|---|
AttributeError | Attribute not found | Typo, wrong object type |
ImportError | Import fails | Module not installed, wrong name |
IndexError | Index out of range | List/tuple too short |
KeyError | Dict key not found | Key doesn’t exist |
NameError | Variable not found | Typo, not defined |
TypeError | Wrong type | Operation on incompatible types |
ValueError | Wrong value | Invalid argument value |
ZeroDivisionError | Division by zero | Divide or modulo by 0 |
FileNotFoundError | File not found | Wrong path, file deleted |
PermissionError | No permission | Insufficient privileges |
RecursionError | Too deep recursion | Infinite recursion |
StopIteration | Iterator exhausted | No more items |
KeyboardInterrupt | User interrupt | Ctrl+C pressed |
Discover more from Altgr Blog
Subscribe to get the latest posts sent to your email.
