You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Basic print (calls __str__)print(obj)
print(f"result: {obj}")
# Debug representation (calls __repr__)print(repr(obj))
print(f"{obj=}") # Python 3.8+: prints "obj=<value>"print(f"{obj=!r}") # Force repr formatting# Unknown objectsprint(f"{type(obj)=}{dir(obj)=}")
# Multiple variables at onceprint(f"{x=}{y=}{result=}")
Pretty Print Structures
frompprintimportpprint# Dictionaries and nested structurespprint(data_dict)
pprint(data_dict, width=120, depth=2)
# Large lists (slice first)pprint(big_list[:10]) # First 10 itemspprint(big_list[-5:]) # Last 5 items# All local variables in functionpprint(locals())
# All instance variables in methodpprint(vars(self))
pprint(self.__dict__) # Alternative
Assertion Debugging
most useful for big loops and deep recursive algorithms
print stack trace (how does code get here?)
# Validate loop invariantsfori, nodeinenumerate(graph):
asserti<1000, f"infinite loop? {i=}{node=}"assertnodeinvisitedornode==start, f"bad state {visited=}"# Check recursion depth/statedefdfs(node, depth=0):
assertdepth<50, f"too deep! {depth=}{node=}"assertnodeisnotNone, f"null node at {depth=}"# Edge cases in algorithmsassertlen(queue) >0orfound, f"empty queue but not found: {visited=}"assertlow<=high, f"binary search bounds crossed: {low=}{high=}{target=}"# Side-effect assertions (runs pprint if condition fails)assertresult>0orpprint(vars()), f"unexpected result: {result=}"assertvalidorpprint(vars(self)), f"invalid state"