python Errors

243 error patterns

python3 fixes

Asyncio event loop already running

RuntimeError: This event loop is already running

  • Use nest_asyncio.apply() to allow nested event loops
  • Use asyncio.run_coroutine_threadsafe() instead of asyncio.run()
python3 fixes

Coroutine never awaited

RuntimeWarning: coroutine '.*' was never awaited

  • Add 'await' before the coroutine call
  • Use asyncio.create_task() to schedule the coroutine
python3 fixes

Asyncio task was cancelled

asyncio\.CancelledError

  • Handle CancelledError in try/except within the task
  • Use asyncio.shield() to protect critical sections from cancellation
python3 fixes

Executor shutdown prevents new task scheduling

RuntimeError: cannot schedule new futures after shutdown

  • Ensure all tasks are submitted before calling executor.shutdown()
  • Use 'with' context manager for ThreadPoolExecutor
python3 fixes

Future attached to different event loop

RuntimeError: Task .* got Future .* attached to a different loop

  • Ensure all coroutines use the same event loop
  • Avoid creating futures in one loop and awaiting in another
python3 fixes

No running event loop in current thread

RuntimeError: no running event loop

  • Use asyncio.run() to start the event loop
  • Use asyncio.new_event_loop() and set it with asyncio.set_event_loop()
python3 fixes

Asyncio wait_for timeout exceeded

TimeoutError.*asyncio\.wait_for

  • Increase the timeout value in asyncio.wait_for()
  • Add retry logic with exponential backoff
python3 fixes

Coroutine already awaited cannot be reused

RuntimeError: cannot reuse already awaited coroutine

  • Create a new coroutine instance for each await
  • Wrap in a function that returns a fresh coroutine each time
python3 fixes

FastAPI 422 validation error on request

422 Unprocessable Entity.*validation error

  • Check request body matches the Pydantic model schema
  • Use Optional[] for nullable fields with default=None
python3 fixes

FastAPI request validation error

fastapi\.exceptions\.RequestValidationError

  • Add custom exception handler with @app.exception_handler(RequestValidationError)
  • Check path parameter types match route definition
python3 fixes

FastAPI dependency injection resolution failure

DependencyInjection.*Depends\(\).*cannot be resolved

  • Ensure dependency function signature matches expected parameters
  • Check that sub-dependencies are properly defined
python3 fixes

FastAPI background task execution error

RuntimeError: BackgroundTask.*after response

  • Return BackgroundTasks in the route function parameter, not manually
  • Ensure background task function doesn't depend on request lifecycle
python3 fixes

FastAPI WebSocket client disconnected

starlette\.websockets\.WebSocketDisconnect

  • Wrap receive() in try/except WebSocketDisconnect
  • Implement heartbeat/ping mechanism to detect stale connections
python3 fixes

SQLAlchemy session transaction already rolled back

sqlalchemy\.exc\.InvalidRequestError: This Session's transaction has been rolled back

  • Call session.rollback() explicitly before retrying
  • Use session.begin() context manager for automatic rollback on exception
python3 fixes

SQLAlchemy accessing attribute on detached instance

sqlalchemy\.exc\.DetachedInstanceError

  • Use eager loading (joinedload/selectinload) to load relationships before detaching
  • Keep the session open while accessing lazy-loaded attributes
python3 fixes

SQLAlchemy stale data during flush

sqlalchemy\.orm\.exc\.StaleDataError

  • Refresh the instance with session.refresh(obj) before modifying
  • Use optimistic locking with version_id_col
python3 fixes

SQLAlchemy lazy load in async session without greenlet

sqlalchemy\.exc\.MissingGreenlet.*lazy load.*within

  • Use selectinload() or joinedload() in the query options
  • Use run_sync() to access lazy attributes in async context
python3 fixes

SQLAlchemy object already attached to another session

sqlalchemy\.exc\.InvalidRequestError.*is already attached to session

  • Use session.merge() instead of session.add() for detached objects
  • Expunge the object from the original session first
python3 fixes

SQLAlchemy query returned no results

sqlalchemy\.exc\.NoResultFound

  • Use .first() instead of .one() if zero results is acceptable
  • Use .one_or_none() to get None instead of an exception
python3 fixes

SQLAlchemy duplicate key integrity error

sqlalchemy\.exc\.IntegrityError.*duplicate key

  • Use INSERT ... ON CONFLICT DO UPDATE (upsert) pattern
  • Check for existence before inserting
python3 fixes

Pydantic v2 validation error

pydantic_core\._pydantic_core\.ValidationError

  • Check field types match the input data
  • Use model_validate() instead of direct constructor for dict input
python3 fixes

Pydantic v2 protected namespace conflict

PydanticUserError.*model_config.*protected_namespaces

  • Set model_config = ConfigDict(protected_namespaces=()) to disable
  • Rename fields that start with 'model_'
python3 fixes

Pydantic v2 discriminated union discriminator missing

PydanticUserError.*discriminator.*not found

  • Add Literal type annotation for the discriminator field in each model
  • Ensure the discriminator field name exists in all union members
python3 fixes

Pydantic v2 schema generation error

pydantic\.errors\.PydanticSchemaGenerationError

  • Use model_rebuild() after all models are defined for forward references
  • Replace complex types with simpler annotations or custom types
python3 fixes

Pydantic v2 unexpected keyword in model init

TypeError.*BaseModel.*__init__.*unexpected keyword argument

  • Check model field names match the keyword arguments
  • Use model_config = ConfigDict(extra='allow') to permit extra fields
python3 fixes

Poetry dependency resolution conflict

poetry\.installer\.installer.*SolverProblemError

  • Run 'poetry update' to refresh lock file
  • Use 'poetry add package@latest' to get compatible version
python3 fixes

Poetry hash mismatch during install

CalledProcessError.*poetry.*install.*hash

  • Delete poetry.lock and run 'poetry lock' to regenerate
  • Clear Poetry cache with 'poetry cache clear pypi --all'
python3 fixes

PDM resolution impossible for dependencies

pdm\.exceptions\.ResolutionImpossible

  • Widen version constraints in pyproject.toml
  • Use 'pdm update --unconstrained' to find a working set
python4 fixes

PyTorch CUDA out of memory

RuntimeError:.*CUDA out of memory

  • Reduce batch size in training/inference
  • Use torch.cuda.empty_cache() to free unused memory
python3 fixes

PyTorch tensor size mismatch

RuntimeError: The size of tensor a \(\d+\) must match the size of tensor b \(\d+\)

  • Check input dimensions with tensor.shape before operations
  • Use tensor.view() or tensor.reshape() to align dimensions
python3 fixes

PyTorch tensor not tracking gradients

RuntimeError: element .* does not require grad and does not have a grad_fn

  • Set requires_grad=True on the tensor
  • Ensure the tensor is part of the computation graph (not detached)
python3 fixes

PyTorch inplace operation breaks autograd

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation

  • Replace inplace operations (+=, relu_) with out-of-place versions
  • Clone the tensor before modifying: x = x.clone()
python3 fixes

PyTorch tensors on different devices

RuntimeError: Expected all tensors to be on the same device

  • Move all tensors to the same device with .to(device)
  • Use model.device to get the model's device and match tensors
python3 fixes

NumPy array memory allocation error

numpy\.core\._exceptions\._ArrayMemoryError

  • Use memory-mapped arrays with np.memmap()
  • Process data in chunks instead of loading all at once
python3 fixes

NumPy broadcasting shape mismatch

ValueError: operands could not be broadcast together with shapes

  • Reshape arrays to compatible dimensions with np.reshape()
  • Use np.expand_dims() to add dimensions for broadcasting
python3 fixes

Pandas SettingWithCopyWarning

SettingWithCopyWarning: A value is trying to be set on a copy of a slice

  • Use .loc[] for label-based assignment: df.loc[mask, col] = value
  • Create an explicit copy with df.copy() before modifying
python3 fixes

Pandas merge with no common columns

MergeError: No common columns to perform merge on

  • Specify left_on and right_on parameters explicitly
  • Rename columns to match before merging
python3 fixes

Pandas DataFrame memory error

MemoryError.*pandas.*DataFrame

  • Use dtype optimization: df = pd.read_csv(file, dtype={'col': 'int32'})
  • Read in chunks with chunksize parameter
python3 fixes

Pandas merge on columns with different types

ValueError: You are trying to merge on.*columns of different types

  • Cast columns to same type: df['col'] = df['col'].astype(str)
  • Use pd.to_numeric() or pd.to_datetime() for type conversion
python3 fixes

Python Protocol class instantiation error

TypeError.*Protocol.*cannot be instantiated

  • Protocols are structural types - implement a concrete class instead
  • Use runtime_checkable decorator if you need isinstance() checks
python3 fixes

Python overload without implementation

TypeError.*overload.*no implementation

  • Add a non-decorated implementation function after all @overload variants
  • The implementation must handle all overload signatures
python3 fixes

TypeVar bound to non-class type

TypeError.*TypeVar.*bound.*is not a class

  • Use a Protocol class as the bound instead
  • Ensure the bound argument is a concrete class or Protocol
python3 fixes

Asyncio future result accessed before set

asyncio\.exceptions\.InvalidStateError: Result is not set

  • Await the future before accessing .result()
  • Check future.done() before accessing the result
python3 fixes

Asyncio timeout used outside task context

RuntimeError: Timeout context manager should be used inside a task

  • Ensure async with asyncio.timeout() is inside an async task
  • Use asyncio.wait_for(coro, timeout) as an alternative
python3 fixes

FastAPI 401 Unauthorized

fastapi\.exceptions\.HTTPException.*status_code.*401

  • Check OAuth2 token is valid and not expired
  • Verify the Authorization header format is 'Bearer <token>'
python3 fixes

Trying to await an async generator

TypeError: object (Async)?Generator.*can't be used in 'await' expression

  • Use 'async for' to iterate over async generators
  • If you need a single value, use anext(generator)
python3 fixes

SQLAlchemy database connection lost

sqlalchemy\.exc\.OperationalError.*server closed the connection unexpectedly

  • Set pool_pre_ping=True in create_engine() to verify connections
  • Configure pool_recycle to a value less than DB timeout
python3 fixes

SQLAlchemy table does not exist

sqlalchemy\.exc\.ProgrammingError.*relation.*does not exist

  • Run alembic upgrade head to apply migrations
  • Use Base.metadata.create_all(engine) for development
python3 fixes

Pydantic v2 serialization error

pydantic.*SerializationError.*unable to serialize

  • Add custom serializer with @field_serializer decorator
  • Use model_config = ConfigDict(arbitrary_types_allowed=True)
python3 fixes

PyTorch CUDA allocation failure with size info

torch\.cuda\.OutOfMemoryError.*tried to allocate

  • Use torch.cuda.memory_summary() to identify memory hogs
  • Implement gradient accumulation to reduce per-step memory
python3 fixes

PyTorch incorrect tensor dimensions

RuntimeError: Expected .* to have .* dimensions but got .* dimensions

  • Use tensor.unsqueeze() to add missing dimensions
  • Use tensor.squeeze() to remove extra dimensions
python3 fixes

PyTorch matrix multiplication shape mismatch

RuntimeError: mat1 and mat2 shapes cannot be multiplied

  • Verify Linear layer in_features matches input size
  • Use tensor.view(-1, correct_size) to reshape before linear layers
python3 fixes

PyTorch optimizer has no parameters

ValueError: optimizer got an empty parameter list

  • Ensure model.parameters() is called after model is fully defined
  • Check that the model has trainable parameters (requires_grad=True)
python3 fixes

Pandas CSV parsing error

pandas\.errors\.ParserError: Error tokenizing data

  • Use error_bad_lines=False (or on_bad_lines='skip' in newer pandas)
  • Specify the correct separator with sep parameter
python3 fixes

Pandas column not in DataFrame index

KeyError:.*not in index

  • Check available columns with df.columns.tolist()
  • Use df.get(key, default) for safe access
python3 fixes

Pandas duplicate index prevents reindexing

ValueError: cannot reindex from a duplicate axis

  • Reset index with df.reset_index(drop=True)
  • Remove duplicates with df[~df.index.duplicated()]
python3 fixes

Poetry Python version incompatible with project

poetry.*Current Python version.*is not allowed by the project

  • Update python requirement in pyproject.toml: python = '^3.9'
  • Use pyenv to install and switch to compatible Python version
python3 fixes

Rye toolchain download failure

rye.*error.*failed to download.*toolchain

  • Check network connectivity and proxy settings
  • Use 'rye toolchain list --include-downloadable' to see available versions
python3 fixes

PDM package missing from lock file

pdm.*PackageWarning.*not found in the lock file

  • Run 'pdm lock' to regenerate the lock file
  • Use 'pdm add <package>' to add it properly
python3 fixes

Pydantic model with unhashable field in set/dict key

TypeError: unhashable type: 'dict'.*Pydantic

  • Use frozenset or tuple instead of list/dict in hashable contexts
  • Implement __hash__ on custom types used as fields
python3 fixes

Pydantic required field missing from input

pydantic.*ValidationError.*Field required

  • Provide the required field in input data
  • Add default value or Optional annotation to make field optional
python3 fixes

SQLAlchemy column not found in mapping

sqlalchemy\.exc\.ArgumentError.*Could not locate any.*column

  • Verify column name matches exactly (case-sensitive)
  • Check that the model's __tablename__ is correct
python3 fixes

SQLAlchemy connection pool exhausted

sqlalchemy\.exc\.TimeoutError.*QueuePool limit

  • Increase pool_size and max_overflow in create_engine()
  • Ensure sessions are closed/returned after use (use context managers)
python3 fixes

SQLAlchemy AsyncSession method mismatch

AttributeError: 'AsyncSession' object has no attribute 'execute'

  • Use 'await session.execute()' - it's async
  • Ensure you imported from sqlalchemy.ext.asyncio
python3 fixes

Asyncio stream read incomplete

asyncio\.IncompleteReadError

  • Handle IncompleteReadError for premature connection close
  • Use readexactly() with try/except for fixed-length reads
python3 fixes

No event loop in non-main thread

RuntimeError: There is no current event loop in thread

  • Create new loop: loop = asyncio.new_event_loop(); asyncio.set_event_loop(loop)
  • Use asyncio.run() which creates and sets a loop automatically
python3 fixes

FastAPI lifespan state not accessible

fastapi.*LifespanState.*not available

  • Use the new lifespan context manager pattern with async generator
  • Access state via request.state instead of app.state in routes
python3 fixes

FastAPI response contains non-serializable object

TypeError: Object of type .* is not JSON serializable.*FastAPI

  • Add custom JSON encoder via json_encoders in model Config
  • Use jsonable_encoder() from fastapi.encoders before returning
python3 fixes

Pydantic invalid discriminator field

ValueError: \[Pydantic\] .* is not a valid discriminator

  • Use a Literal type for the discriminator field in each variant
  • Ensure the discriminator field is required (not Optional)
python3 fixes

Pydantic model_validator before mode type error

pydantic.*model_validator.*mode='before'.*TypeError

  • In mode='before', input can be dict or the raw input - handle both
  • Use @model_validator(mode='wrap') for more control
python3 fixes

PyTorch backward on non-scalar tensor

torch\.autograd\..*grad can be implicitly created only for scalar outputs

  • Call .sum() or .mean() on the loss before .backward()
  • Pass gradient argument to .backward() for non-scalar tensors
python3 fixes

PyTorch second backward pass without retain_graph

RuntimeError: Trying to backward through the graph a second time

  • Use loss.backward(retain_graph=True) if you need multiple passes
  • Restructure code to avoid needing multiple backward passes
python3 fixes

Pandas merge with duplicate keys

pandas\.errors\.MergeError.*merge keys.*not unique in (left|right) dataset

  • Use validate='one_to_one' to detect and raise early
  • Deduplicate before merge: df.drop_duplicates(subset=['key'])
python3 fixes

Pandas deprecated axis=1 in groupby

FutureWarning.*DataFrame\.groupby with axis=1 is deprecated

  • Use df.T.groupby(...) then transpose back
  • Switch to using .apply() across columns instead
python3 fixes

NumPy singular matrix in linear algebra

numpy\.linalg\.LinAlgError: Singular matrix

  • Use np.linalg.pinv() (pseudo-inverse) instead of np.linalg.inv()
  • Add regularization: matrix + eps * np.eye(n)
python3 fixes

NumPy arithmetic overflow

RuntimeWarning: overflow encountered in (multiply|exp|power)

  • Use larger dtype (float64 instead of float32)
  • Apply log-space computation for very large values
python3 fixes

Module not found in Poetry environment

ModuleNotFoundError: No module named '.*'.*poetry

  • Run 'poetry install' to install dependencies
  • Ensure you're running within the venv: 'poetry run python ...'
python3 fixes

SQLAlchemy unconsumed column names in INSERT

sqlalchemy\.exc\.CompileError.*Unconsumed column names

  • Remove columns from values() that don't exist in the table
  • Check column names match table definition exactly
python3 fixes

Alembic target database not up to date

alembic\.util\.exc\.CommandError.*Target database is not up to date

  • Run 'alembic upgrade head' before generating new migration
  • Use 'alembic stamp head' to mark current state if manually migrated
python3 fixes

Alembic can't locate migration revision

alembic\.util\.exc\.CommandError.*Can't locate revision

  • Check migration files exist in alembic/versions/
  • Verify alembic_version table has a valid revision hash
python3 fixes

FastAPI 403 Forbidden

fastapi\.exceptions\.HTTPException.*status_code.*403

  • Verify user has required permissions/roles
  • Check CORS configuration allows the origin
python3 fixes

Pydantic issubclass error with type annotation

TypeError: issubclass\(\) arg 1 must be a class.*Pydantic

  • Use typing.get_origin() and typing.get_args() for generic types
  • Wrap complex annotations in Annotated[] with proper metadata
python3 fixes

PyTorch distributed NCCL communication error

torch\.distributed.*NCCL error.*unhandled system error

  • Set NCCL_DEBUG=INFO for detailed error messages
  • Check all GPUs are accessible and CUDA versions match
python3 fixes

PyTorch DataLoader worker killed

RuntimeError: DataLoader worker.*is killed by signal

  • Reduce num_workers in DataLoader
  • Increase shared memory (--shm-size in Docker)
python3 fixes

Pandas datetime out of bounds

pandas\.errors\.OutOfBoundsDatetime

  • Use pd.Timestamp.min/max to check bounds before parsing
  • Set errors='coerce' in pd.to_datetime() to replace invalid with NaT
python3 fixes

Pandas assignment length mismatch

ValueError: Length of values.*does not match length of index

  • Verify the array/list length matches DataFrame index length
  • Reset index before assignment: df.reset_index(drop=True)
python3 fixes

SQLAlchemy relationship copying column warning

sqlalchemy\.exc\.SAWarning.*relationship .* will copy column

  • Set overlaps parameter on relationship: overlaps='other_rel'
  • Use back_populates instead of backref for explicit relationships
python3 fixes

Protocol with attributes can't use issubclass

TypeError: Protocols with non-method members don't support issubclass

  • Only use isinstance() for runtime_checkable Protocols with non-method members
  • Remove @runtime_checkable if structural checking isn't needed at runtime
python3 fixes

Pydantic model inheritance from invalid base

TypeError: type '.*' is not an acceptable base type.*Pydantic

  • Ensure base class inherits from BaseModel
  • Use composition instead of inheritance for non-Pydantic types
python3 fixes

Asyncio barrier broken due to task failure

asyncio\.BrokenBarrierError

  • Wrap barrier.wait() in try/except and handle BrokenBarrierError
  • Reset the barrier with barrier.reset() if recovery is possible
python3 fixes

Unclosed SSL socket resource warning

ResourceWarning: unclosed.*<ssl\.SSLSocket

  • Use async with for aiohttp sessions
  • Call await session.close() in a finally block
python3 fixes

TorchScript type error with None value

torch\.jit\.Error.*expected.*Tensor.*got.*None

  • Use Optional[torch.Tensor] annotation for nullable returns
  • Add explicit None checks before tensor operations in scripted code
python3 fixes

NumPy axis out of bounds

numpy\.AxisError: axis .* is out of bounds for array of dimension

  • Check array dimensions with arr.ndim before specifying axis
  • Use axis=-1 for the last dimension instead of hardcoding
python3 fixes

FastAPI response_model validation failure

fastapi\.routing\.APIRoute.*response_model.*validation error

  • Ensure returned data matches response_model schema exactly
  • Use response_model_exclude_unset=True for partial responses
python3 fixes

Pydantic computed_field with default value

pydantic\.errors\.PydanticUserError.*computed_field.*cannot have default

  • Remove default value from @computed_field decorated property
  • Computed fields derive their value from the property body
python3 fixes

SQLAlchemy duplicate identity in session

sqlalchemy\.exc\.InvalidRequestError.*Can't attach instance.*another instance with key.*already present

  • Use session.merge() to reconcile with existing identity
  • Query for existing record first: session.get(Model, id)
python3 fixes

Pydantic v2 import in v1 environment

ImportError: cannot import name 'field_validator' from 'pydantic'

  • Upgrade pydantic: pip install 'pydantic>=2.0'
  • Use @validator instead of @field_validator for Pydantic v1
python3 fixes

Async generator concurrent access error

RuntimeError: async generator.*asend.*already running

  • Ensure only one consumer iterates the async generator at a time
  • Use asyncio.Lock() to serialize access to the generator
python3 fixes

Pandas cannot cast NaN to integer

pd\.errors\.IntCastingNaNError.*Cannot convert non-finite values

  • Use pd.Int64Dtype() (nullable integer): df['col'].astype('Int64')
  • Fill NaN before casting: df['col'].fillna(0).astype(int)
python3 fixes

PyTorch unsupported dtype for operation

torch\..*ComplexHalf.*not supported

  • Cast tensor to supported dtype: tensor.to(torch.float32)
  • Check operation documentation for supported dtypes
python3 fixes

PyTorch CUDA Out of Memory

CUDA out of memory\. Tried to allocate [\d.]+ [GM]iB

  • Reduce batch size
  • Use torch.cuda.empty_cache() between iterations
python3 fixes

PyTorch Tensor Dimension Mismatch

RuntimeError: The size of tensor a \(\d+\) must match the size of tensor b \(\d+\)

  • Check tensor shapes with .shape before operations
  • Use .view() or .reshape() to align dimensions
python3 fixes

PyTorch Autograd Graph Already Freed

RuntimeError: Trying to backward through the graph a second time

  • Set retain_graph=True in .backward() if needed
  • Detach tensors with .detach() when reusing
python3 fixes

PyTorch DataLoader Worker Killed

RuntimeError: DataLoader worker \(pid \d+\) is killed by signal

  • Reduce num_workers in DataLoader
  • Increase system shared memory (--shm-size in Docker)
python3 fixes

PyTorch Mixed Device Tensors

RuntimeError: Expected all tensors to be on the same device, but found at least two devices

  • Move all tensors to same device with .to(device)
  • Check model.device and input.device match
python3 fixes

PyTorch Inplace Operation Breaks Autograd

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation

  • Replace inplace ops (x += y) with out-of-place (x = x + y)
  • Use .clone() before modifying tensors needed for grad
python3 fixes

PyTorch CUDA OOM Error Class

torch\.cuda\.OutOfMemoryError: CUDA out of memory

  • Use mixed precision training with torch.cuda.amp
  • Implement gradient accumulation over smaller batches
python3 fixes

PyTorch Distributed NCCL Failure

RuntimeError: NCCL communicator was aborted

  • Set NCCL_DEBUG=INFO for detailed error logs
  • Check network connectivity between nodes
python3 fixes

PyTorch Matrix Multiplication Shape Error

RuntimeError: mat1 and mat2 shapes cannot be multiplied \(\d+x\d+ and \d+x\d+\)

  • Verify linear layer in_features matches input tensor last dim
  • Use .T or .transpose() to align matrices
python3 fixes

PyTorch Model/Input Device Mismatch

RuntimeError: Input type \(torch\.cuda\.FloatTensor\) and weight type \(torch\.FloatTensor\) should be the same

  • Call model.to(device) before inference
  • Move input tensor with input.to(device)
python3 fixes

PyTorch CUDA Device Assert

RuntimeError: CUDA error: device-side assert triggered

  • Run with CUDA_LAUNCH_BLOCKING=1 for exact line
  • Check label indices are within num_classes range
python3 fixes

PyTorch Dtype Mismatch Float vs Half

RuntimeError: expected scalar type Float but found Half

  • Cast tensor with .float() or .half() as needed
  • Use torch.cuda.amp.autocast() for automatic mixed precision
python3 fixes

PyTorch Concatenation Dimension Mismatch

RuntimeError: Sizes of tensors must match except in dimension \d+

  • Verify all tensors have same shape except concat dim
  • Use padding to equalize dimensions before concat
python3 fixes

PyTorch CUDA Fork Error

RuntimeError: Cannot re-initialize CUDA in forked subprocess

  • Set multiprocessing start method to 'spawn'
  • Initialize CUDA after fork, not before
python3 fixes

PyTorch Loss Function Size Mismatch

ValueError: Target size \(torch\.Size\(\[.*\]\)\) must be the same as input size

  • Squeeze predictions with .squeeze() to match target shape
  • Verify batch dimensions align between pred and target
python3 fixes

PyTorch CPU Tensor Passed to CUDA Op

RuntimeError: Expected object of device type cuda but got device type cpu

  • Move tensor to GPU with tensor.cuda() or tensor.to('cuda')
  • Check all inputs in forward() are on correct device
python3 fixes

PyTorch Non-Scalar Backward

RuntimeError: grad can be implicitly created only for scalar outputs

  • Reduce loss to scalar with .mean() or .sum()
  • Pass gradient argument to .backward(gradient=...)
python3 fixes

PyTorch cuDNN Unsupported Config

RuntimeError: cuDNN error: CUDNN_STATUS_NOT_SUPPORTED

  • Set torch.backends.cudnn.enabled = False to debug
  • Check input dimensions meet cuDNN requirements
python3 fixes

PyTorch Stack Unequal Tensors

RuntimeError: stack expects each tensor to be equal size

  • Pad sequences to same length before stacking
  • Use torch.nn.utils.rnn.pad_sequence()
python3 fixes

PyTorch View Non-Contiguous Tensor

RuntimeError: view size is not compatible with input tensor's size and stride

  • Call .contiguous() before .view()
  • Use .reshape() instead which handles non-contiguous
python3 fixes

TensorFlow SavedModel Not Found

tensorflow\.python\.framework\.errors_impl\.NotFoundError: SavedModel file does not exist

  • Verify saved_model.pb exists in the directory
  • Use correct path without trailing slash
python3 fixes

TensorFlow Disconnected Graph Error

tensorflow\.python\.framework\.errors_impl\.InvalidArgumentError: Graph disconnected

  • Ensure all layers are connected in model definition
  • Check for orphaned layers not linked to input/output
python3 fixes

TensorFlow Invalid Optimizer

ValueError: Could not interpret optimizer identifier

  • Use string name like 'adam' or instance tf.keras.optimizers.Adam()
  • Check optimizer is from tf.keras.optimizers not tf.train
python3 fixes

TensorFlow NaN/Inf Loss

tensorflow.*LossTensor is inf or nan

  • Add tf.debugging.check_numerics() to detect source
  • Reduce learning rate
python3 fixes

TensorFlow TPU Not Available

RuntimeError: TPU.*not available

  • Initialize TPU with tf.distribute.cluster_resolver.TPUClusterResolver()
  • Call tf.tpu.experimental.initialize_tpu_system()
python3 fixes

TensorFlow Layer Input Incompatible

ValueError: Input \d+ of layer .* is incompatible with the layer

  • Check input_shape parameter matches actual input dimensions
  • Add Input layer with correct shape specification
python3 fixes

TensorFlow GPU OOM

ResourceExhaustedError: OOM when allocating tensor

  • Set tf.config.experimental.set_memory_growth(gpu, True)
  • Reduce batch size in training config
python3 fixes

TensorFlow Shape Incompatibility

InvalidArgumentError: Incompatible shapes: \[\d+.*\] vs\. \[\d+.*\]

  • Use tf.debugging.assert_shapes() to validate
  • Reshape with tf.reshape() before the operation
python3 fixes

TensorFlow Keras Shape Compile Error

ValueError: Shapes \(.*\) and \(.*\) are incompatible

  • Verify model.compile() metrics match output shape
  • Check loss function expects correct output format
python3 fixes

TensorFlow Operation Cancelled

AbortedError: .* was cancelled

  • Check for session timeout in distributed training
  • Increase RPC timeout for remote operations
python3 fixes

HuggingFace Tokenizer Type Mismatch

The tokenizer class you load from this checkpoint is not the same type

  • Use AutoTokenizer.from_pretrained() instead of specific class
  • Ensure tokenizer and model are from same checkpoint
python3 fixes

HuggingFace Model File Missing

RuntimeError: .* does not appear to have a file named pytorch_model\.bin

  • Check if model uses safetensors format instead
  • Download with from_pretrained(model_name, use_safetensors=True)
python3 fixes

HuggingFace Model Too Large for GPU

torch\.cuda\.OutOfMemoryError.*loading.*model

  • Load with device_map='auto' for automatic sharding
  • Use load_in_8bit=True or load_in_4bit=True with bitsandbytes
python3 fixes

HuggingFace Pipeline Model Incompatible

PipelineException: The model .* is not compatible with this pipeline

  • Verify model task matches pipeline type (e.g., text-generation)
  • Specify task explicitly in pipeline() call
python3 fixes

HuggingFace Tokenizer Overflow

ValueError: Unable to create tensor.*overflowing values

  • Set truncation=True in tokenizer call
  • Specify max_length parameter
python3 fixes

HuggingFace Training NaN Loss

FloatingPointError: Overflow.*loss became NaN

  • Enable fp16=True with loss scaling in TrainingArguments
  • Reduce learning rate by 10x
python3 fixes

HuggingFace Embedding Index OOB

IndexError: index out of range in self.*Embedding

  • Resize embeddings with model.resize_token_embeddings(len(tokenizer))
  • Check tokenizer vocab size matches model embedding size
python3 fixes

HuggingFace Config Missing

OSError: .* does not appear to have a file named config\.json

  • Verify model name/path is correct on HuggingFace Hub
  • Check internet connection for model download
python3 fixes

HuggingFace Wrong Input Type to Tokenizer

ValueError: text input must of type `str`.*but is.*<class 'list'>

  • Pass single string or list of strings to tokenizer
  • Use tokenizer.batch_encode_plus() for list inputs
python3 fixes

HuggingFace Attention Mask Shape Error

RuntimeError: The expanded size of the tensor.*must match the existing size

  • Ensure attention_mask shape matches input_ids shape
  • Pad both input_ids and attention_mask to same length
python3 fixes

LangChain Output Parser Failed

OutputParserException: Could not parse LLM output

  • Add output_fixing_parser with retry logic
  • Improve prompt to enforce output format
python3 fixes

LangChain Vector Store Document Not Found

ValueError: Could not find.*in vectorstore

  • Verify documents were added to vectorstore before query
  • Check embedding model matches between index and query time
python3 fixes

LangChain Chain Missing Input Variables

langchain.*ChainError.*missing.*input_variables

  • Check all required variables in prompt template are passed
  • Verify chain.invoke() dict keys match template variables
python3 fixes

LangChain Retriever Failure

RetrieverError: Failed to retrieve documents

  • Check vectorstore connection is alive
  • Verify embedding dimensions match stored embeddings
python3 fixes

LangChain Pydantic Validation Error

langchain.*ValidationError.*field required

  • Provide all required fields in model/chain config
  • Check API key environment variables are set
python3 fixes

OpenAI API Rate Limit

openai\.RateLimitError: Rate limit reached

  • Implement exponential backoff with tenacity or backoff library
  • Use tiktoken to estimate tokens and batch efficiently
python3 fixes

OpenAI Token Limit Exceeded

openai\.BadRequestError:.*maximum context length.*tokens.*you requested \d+ tokens

  • Truncate input to fit within model context window
  • Use tiktoken to count tokens before sending
python3 fixes

OpenAI Function Calling Schema Error

openai\.BadRequestError:.*Invalid schema for function

  • Validate JSON Schema before passing to API
  • Ensure parameters.type is 'object' with properties defined
python3 fixes

OpenAI API Connection Failed

openai\.APIConnectionError: Connection error

  • Check network connectivity and proxy settings
  • Set httpx timeout with timeout=httpx.Timeout(60.0)
python3 fixes

OpenAI Streaming Response Error

openai.*Stream.*error.*incomplete

  • Add try/except around stream iteration with retry
  • Set stream_options={'include_usage': True} to detect end
python3 fixes

OpenAI Invalid API Key

openai\.AuthenticationError: Incorrect API key provided

  • Verify OPENAI_API_KEY env var is set correctly
  • Check key starts with sk- and has no trailing whitespace
python3 fixes

OpenAI Content Filter Triggered

openai\.BadRequestError:.*content_filter

  • Rephrase input to avoid triggering content policy
  • Add system message clarifying legitimate use case
python3 fixes

OpenAI Invalid Tool Choice

openai\.BadRequestError:.*'tool_choice'.*not.*valid

  • Use tool_choice='auto' or {'type':'function','function':{'name':'...'}}
  • Verify function name in tool_choice exists in tools list
python3 fixes

Ollama Model Not Found

Error: model .* not found.*try pulling it first

  • Run 'ollama pull <model-name>' to download model
  • Check available models with 'ollama list'
python3 fixes

Ollama Context Length Exceeded

context length exceeded.*maximum.*\d+

  • Set num_ctx parameter in model options to increase context
  • Truncate input to fit within model context window
python3 fixes

Ollama Quantization Format Error

error loading model.*quantization.*not supported

  • Download correct quantization format for your hardware
  • Use Q4_0 or Q4_K_M for lower memory systems
python3 fixes

Ollama Server Not Running

connection refused.*localhost:11434

  • Start Ollama with 'ollama serve' command
  • Check if port 11434 is available or change OLLAMA_HOST
python3 fixes

PyTorch Model Parallelism OOM

RuntimeError: CUDA out of memory.*model parallel

  • Balance layer distribution across GPUs more evenly
  • Use pipeline parallelism with smaller micro-batches
python3 fixes

PyTorch Missing Model Weight

RuntimeError: module.*has no attribute.*weight

  • Load state_dict with strict=False to see missing keys
  • Verify checkpoint matches model architecture version
python3 fixes

PyTorch Memory Format Mismatch

RuntimeError: Expected.*channels_last.*but got.*contiguous_format

  • Convert tensor with .to(memory_format=torch.channels_last)
  • Ensure model and input use same memory format
python3 fixes

PyTorch Scheduler Before Optimizer Step

RuntimeError: Detected.*call of.*lr_scheduler\.step\(\) before.*optimizer\.step\(\)

  • Move scheduler.step() after optimizer.step()
  • Follow order: loss.backward() → optimizer.step() → scheduler.step()
python3 fixes

PyTorch Tensor No Grad for Backward

RuntimeError: element \d+ of tensors does not require grad

  • Set requires_grad=True on tensor
  • Verify tensor is part of computation graph
python3 fixes

PyTorch Non-Tensor Grad Requirement

RuntimeError: Only Tensors.*can.*require gradients

  • Convert numpy array to tensor with torch.from_numpy()
  • Ensure Variable is replaced with Tensor (deprecated API)
python3 fixes

PyTorch Distributed System Error

torch\.distributed\.DistBackendError: NCCL error.*unhandled system error

  • Check GPU driver version compatibility
  • Set NCCL_P2P_DISABLE=1 if P2P communication fails
python3 fixes

PyTorch Unexpected Dtype in Operation

RuntimeError: Expected.*dtype.*but got.*dtype

  • Cast tensors with .to(dtype=torch.float32)
  • Check model expects float32 vs float16 input
python3 fixes

HuggingFace Trainer Missing Dataset

ValueError: Trainer requires a train_dataset or a data_collator

  • Pass train_dataset to Trainer constructor
  • Create dataset with datasets.Dataset.from_dict()
python3 fixes

HuggingFace Trainer OOM During Training

OutOfMemoryError.*during.*Trainer\.train\(\)

  • Set per_device_train_batch_size=1 with gradient_accumulation_steps
  • Enable fp16=True or bf16=True in TrainingArguments
python3 fixes

HuggingFace Batch Size Mismatch in Loss

ValueError: Expected input batch_size.*to match target batch_size

  • Verify labels shape matches model output shape
  • Check data collator produces correct batch format
python3 fixes

HuggingFace BitsAndBytes CUDA Error

ImportError: .*bitsandbytes.*CUDA

  • Install bitsandbytes with pip install bitsandbytes
  • Verify CUDA toolkit version matches bitsandbytes requirements
python3 fixes

HuggingFace Feature Count Mismatch

ValueError: The model.*expects.*features.*but got

  • Verify dataset columns match model expected inputs
  • Remove or rename extra columns with dataset.remove_columns()
python3 fixes

LangChain Callback Handler Error

langchain.*callbacks.*error.*handler

  • Implement all required methods in custom callback handler
  • Use AsyncCallbackHandler for async chains
python3 fixes

LangChain Memory Key Mismatch

langchain.*memory.*ConversationBufferMemory.*key

  • Set memory_key parameter to match chain's expected input
  • Use input_key and output_key params in memory config
python3 fixes

LangChain Text Splitter Invalid Config

langchain.*text_splitter.*chunk_size.*must be.*chunk_overlap

  • Set chunk_size larger than chunk_overlap
  • Typical values: chunk_size=1000, chunk_overlap=200
python3 fixes

LangChain ChromaDB Duplicate ID

chromadb.*DuplicateIDError

  • Generate unique IDs for each document chunk
  • Use hash of content + metadata as ID
python3 fixes

LangChain Agent Output Parse Failure

langchain.*agent.*Could not parse LLM output

  • Use handle_parsing_errors=True in AgentExecutor
  • Add format instructions to agent prompt
python3 fixes

OpenAI Internal Server Error

openai\.InternalServerError: The server had an error

  • Implement retry with exponential backoff
  • Try alternative model if specific model is overloaded
python3 fixes

OpenAI Response Truncated by Max Tokens

openai.*finish_reason.*length.*max_tokens

  • Increase max_tokens parameter in API call
  • Implement continuation logic to stitch multiple responses
python3 fixes

OpenAI Empty Message Content

openai.*invalid_request_error.*messages.*must.*content

  • Ensure all messages have non-null content field
  • Remove messages with None content from history
python3 fixes

TensorFlow Variable Not Initialized

tensorflow\.python\.framework\.errors_impl\.FailedPreconditionError:.*not initialized

  • Call tf.compat.v1.global_variables_initializer() in TF1 code
  • Use tf.Variable with initial_value in TF2
python3 fixes

TensorFlow Mixed Precision Underflow

tensorflow.*mixed_precision.*loss_scale.*underflow

  • Increase initial_scale in LossScaleOptimizer
  • Use dynamic loss scaling with longer scale_window
python3 fixes

TensorFlow No Gradients Available

ValueError: No gradients provided for any variable

  • Verify loss is connected to trainable variables
  • Check tf.GradientTape watches the correct variables
python3 fixes

TensorFlow Logits Labels Batch Mismatch

InvalidArgumentError:.*logits and labels must have the same first dimension

  • Verify batch sizes match between predictions and labels
  • Check for inadvertent shape broadcasting
python3 fixes

TensorFlow Keras API Method Missing

tensorflow.*keras.*Model.*has no attribute.*predict_proba

  • Use model.predict() instead of predict_proba()
  • Wrap model output with sigmoid/softmax for probabilities
python3 fixes

TensorFlow Placeholder Not Fed (TF1)

INVALID_ARGUMENT: You must feed a value for placeholder tensor

  • Migrate to TF2 eager mode eliminating placeholders
  • Provide all required feed_dict values in session.run()
python3 fixes

TensorFlow TPU Compilation Timeout

RuntimeError:.*DeadlineExceeded.*TPU.*compilation

  • Reduce model size or batch size for faster compilation
  • Use tf.function with jit_compile=False for debugging
python3 fixes

HuggingFace Hub Authentication Error

huggingface_hub.*HTTPError: 401.*token

  • Run huggingface-cli login with valid token
  • Set HF_TOKEN environment variable
python3 fixes

HuggingFace Missing Padding Token

ValueError: Asking to pad but the tokenizer does not have a padding token

  • Set tokenizer.pad_token = tokenizer.eos_token
  • Add pad token with tokenizer.add_special_tokens({'pad_token': '[PAD]'})
python3 fixes

PyTorch CUDA Compute Capability Mismatch

CUDA error: no kernel image is available for execution on the device

  • Install PyTorch built for your GPU architecture
  • Check GPU compute capability with nvidia-smi
python3 fixes

PyTorch Numpy Not Available

RuntimeError: Numpy is not available

  • Install numpy with pip install numpy
  • Check numpy version compatibility with PyTorch version
python3 fixes

LangChain LCEL Runnable Input Error

langchain.*RunnableSequence.*error.*input

  • Verify input dict keys match RunnablePassthrough assignments
  • Use RunnableLambda to transform inputs between steps
python3 fixes

FAISS Index Dimension Mismatch

faiss.*IndexError.*dimension

  • Verify embedding dimension matches index dimension at creation
  • Rebuild index with correct dimension: faiss.IndexFlatL2(dim)
python3 fixes

OpenAI JSON Mode Missing Instruction

openai.*json_mode.*must.*contain.*JSON

  • Add 'respond in JSON' to system or user message
  • Include JSON format example in the prompt
python3 fixes

PyTorch Checkpoint Weight Size Mismatch

RuntimeError:.*weight.*copying from.*size.*different

  • Use strict=False in load_state_dict and handle missing keys
  • Verify model architecture matches checkpoint version
python3 fixes

HuggingFace Generation Config Conflict

ValueError:.*GenerationConfig.*max_new_tokens.*max_length

  • Use max_new_tokens instead of max_length for generate()
  • Remove conflicting generation parameters
python3 fixes

HuggingFace Accelerate Device Map Error

accelerate.*dispatch.*model.*device_map.*error

  • Install accelerate: pip install accelerate
  • Use device_map='auto' for automatic allocation
python3 fixes

HuggingFace Deprecated API Argument

TypeError: .* got an unexpected keyword argument 'return_dict'

  • Update transformers to latest version
  • Remove deprecated arguments from model forward call
python3 fixes

LangChain Embedding Dimension Changed

langchain.*embeddings.*dimension.*mismatch

  • Delete and recreate vector store with new embeddings
  • Ensure same embedding model is used for index and query
python3 fixes

OpenAI Model Access Denied

openai\.PermissionDeniedError:.*model.*does not exist or you do not have access

  • Verify model name is correct (e.g., gpt-4 vs gpt-4-turbo)
  • Check API key has access to requested model
python3 fixes

Ollama Insufficient GPU Memory

ollama.*gpu.*memory.*insufficient

  • Use smaller quantization (Q4_0 instead of Q8_0)
  • Set OLLAMA_NUM_GPU=0 to run on CPU
python3 fixes

PyTorch Flash Attention Dtype Error

RuntimeError: FlashAttention.*not supported.*dtype

  • Cast input to float16 or bfloat16 for Flash Attention
  • Set attn_implementation='eager' to disable Flash Attention
python3 fixes

JWT Invalid Structure (Python)

JWT.*decode.*invalid number of segments

  • Check token has exactly 3 base64url segments separated by dots
  • Verify no Bearer prefix is included in the token value
python3 fixes

Python JWT Not Enough Segments

jwt\.exceptions\.DecodeError: Not enough segments

  • Ensure complete token is passed (header.payload.signature)
  • Check token wasn't truncated during transmission
python3 fixes

Python JWT Invalid Algorithm

jwt\.exceptions\.InvalidAlgorithmError

  • Specify algorithms=['RS256'] in decode() call
  • Never allow 'none' or HS256 when expecting RS256
python3 fixes

Unsupported operand types

TypeError: unsupported operand type\(s\) for (.+): '(.+)' and '(.+)'

  • Cast operands to compatible types (e.g., int(x) + int(y))
  • Check that variables hold the expected types before the operation
python3 fixes

Object is not callable

TypeError: '(.+)' object is not callable

  • Remove parentheses if you're accessing a property, not calling a function
  • Check if you accidentally shadowed a built-in function (e.g., list = [1,2])
python3 fixes

Unhashable type used as dict key or in set

TypeError: unhashable type: '(.+)'

  • Convert list to tuple before using as a dict key or set element
  • Use frozenset() instead of set() for hashable set keys
python3 fixes

Wrong type passed to function

TypeError: (.+) expected (.+), got (.+)

  • Cast the argument to the expected type (e.g., int(), str(), bytes())
  • Check function signature for expected parameter types
python3 fixes

Wrong number of arguments

TypeError: (.+) takes (\d+) positional arguments? but (\d+) (?:was|were) given

  • Check function definition for the correct number of parameters
  • Add 'self' as the first parameter if this is an instance method
python3 fixes

Cannot unpack non-iterable object

TypeError: cannot unpack non-iterable (.+) object

  • Ensure the function returns a tuple/list before unpacking (a, b = func())
  • Check that the right-hand side is iterable
python3 fixes

Object has no attribute

AttributeError: '(.+)' object has no attribute '(.+)'

  • Check for typos in the attribute/method name
  • Verify the object is the type you expect (print(type(obj)))
python3 fixes

NoneType has no attribute

AttributeError: 'NoneType' object has no attribute '(.+)'

  • A function returned None unexpectedly — check return statements
  • Add a None check before accessing the attribute: if obj is not None
python3 fixes

Module not found

ModuleNotFoundError: No module named '(.+)'

  • Install the package: pip install <module_name>
  • Activate your virtual environment before running
python3 fixes

Cannot import name from module

ImportError: cannot import name '(.+)' from '(.+)'

  • Check for circular imports between modules
  • Verify the name exists in the target module (may have been renamed or removed)
python3 fixes

Unexpected indent

IndentationError: unexpected indent

  • Remove extra spaces/tabs at the beginning of the line
  • Ensure consistent indentation (all spaces or all tabs, not mixed)
python3 fixes

Expected an indented block

IndentationError: expected an indented block

  • Add a body to the if/for/def/class block (use 'pass' as placeholder)
  • Check that the line after a colon is properly indented
python3 fixes

Invalid syntax

SyntaxError: invalid syntax

  • Check the line above for a missing closing parenthesis, bracket, or quote
  • Ensure colons are present after if/for/while/def/class statements
python3 fixes

Unexpected end of file

SyntaxError: unexpected EOF while parsing

  • Add a missing closing parenthesis, bracket, or brace
  • Ensure multi-line strings are properly closed with matching quotes
python3 fixes

f-string syntax error

SyntaxError: f-string: (.+)

  • Escape braces in f-strings with double braces: {{ and }}
  • Don't use backslashes inside f-string expressions — assign to a variable first
python3 fixes

Invalid literal for int()

ValueError: invalid literal for int\(\) with base (\d+): '(.+)'

  • Strip whitespace before conversion: int(value.strip())
  • Validate the string contains only digits before converting
python3 fixes

Too many values to unpack

ValueError: too many values to unpack \(expected (\d+)\)

  • Add more variables on the left side to match the iterable length
  • Use *rest to capture extra values: a, b, *rest = iterable
python3 fixes

Not enough values to unpack

ValueError: not enough values to unpack \(expected (\d+), got (\d+)\)

  • Reduce the number of variables on the left side
  • Verify the iterable contains enough elements
python3 fixes

Dictionary key not found

KeyError: (.+)

  • Use dict.get(key, default) to provide a fallback value
  • Check key existence with 'if key in dict' before accessing
python3 fixes

List index out of range

IndexError: list index out of range

  • Check list length before accessing: if len(lst) > index
  • Use try/except IndexError for safe access
python3 fixes

File or directory not found

FileNotFoundError: \[Errno 2\] No such file or directory: '(.+)'

  • Use absolute paths or verify working directory with os.getcwd()
  • Check file path for typos and correct OS path separators
python3 fixes

Name is not defined

NameError: name '(.+)' is not defined

  • Check for typos in the variable or function name
  • Ensure the variable is defined before it's used (order matters)
python3 fixes

Maximum recursion depth exceeded

RecursionError: maximum recursion depth exceeded

  • Add or fix the base case in your recursive function
  • Convert to an iterative approach using a stack/queue
python3 fixes

Permission denied

PermissionError: \[Errno 13\] Permission denied: '(.+)'

  • Run with elevated privileges (sudo on Linux/macOS, admin on Windows)
  • Check file permissions: os.chmod() or fix in file explorer
python3 fixes

Address already in use

OSError: \[Errno 98\] Address already in use

  • Kill the process using the port: lsof -i :PORT then kill -9 PID
  • Use a different port for your server
python3 fixes

pip cannot find package version

ERROR: Could not find a version that satisfies the requirement (.+)

  • Check the package name spelling on PyPI (pypi.org)
  • Upgrade pip: pip install --upgrade pip
python3 fixes

Externally managed environment (PEP 668)

error: externally-managed-environment

  • Create a virtual environment: python -m venv .venv && source .venv/bin/activate
  • Use pipx for CLI tools: pipx install <package>
python3 fixes

Django: no such table

django\.db\.utils\.OperationalError: no such table: (.+)

  • Run migrations: python manage.py makemigrations && python manage.py migrate
  • Ensure the app is in INSTALLED_APPS in settings.py
python3 fixes

Django: template not found

django\.template\.exceptions\.TemplateDoesNotExist: (.+)

  • Add the template directory to TEMPLATES[0]['DIRS'] in settings.py
  • Ensure APP_DIRS is True and the app is in INSTALLED_APPS
python3 fixes

Django/Flask: CSRF verification failed

Forbidden \(CSRF (?:cookie|token) not set\)|CSRF verification failed

  • Add {% csrf_token %} inside your <form> tag in Django templates
  • Include X-CSRFToken header in AJAX requests
python3 fixes

Flask/Jinja2: template not found

jinja2\.exceptions\.TemplateNotFound: (.+)

  • Place templates in a 'templates/' folder relative to your app
  • Set template_folder parameter in Flask(__name__, template_folder='...')
python3 fixes

Flask: working outside application context

RuntimeError: Working outside of application context

  • Wrap code in: with app.app_context():
  • Use @app.before_request or access within a route handler
python3 fixes

Module not found — virtual environment not activated

ModuleNotFoundError: No module named '(.+)'\.?.*(?:Did you mean|\(venv\))

  • Activate virtual environment: source .venv/bin/activate (Linux/Mac) or .venv\Scripts\activate (Windows)
  • Ensure your IDE/terminal is using the correct Python interpreter from the venv
python3 fixes

Unicode decode error

UnicodeDecodeError: '(.+)' codec can't decode byte

  • Specify encoding when opening files: open(file, encoding='utf-8')
  • Try 'latin-1' or 'cp1252' for legacy Windows files
python3 fixes

JSON decode error

json\.decoder\.JSONDecodeError: (.+)

  • Validate JSON format — check for trailing commas, single quotes, or unquoted keys
  • Ensure the response is actually JSON (check Content-Type header)
python3 fixes

Requests connection error

requests\.exceptions\.ConnectionError: (.+)

  • Check that the target server is running and accessible
  • Verify the URL scheme (http vs https) and port number
python3 fixes

Django: database integrity constraint violation

django\.db\.utils\.IntegrityError: (.+) violates (.+) constraint

  • Check for duplicate values on unique fields before saving
  • Use get_or_create() instead of create() to avoid duplicates
python3 fixes

Object not JSON serializable

TypeError: Object of type (.+) is not JSON serializable

  • Convert datetime to string: obj.isoformat()
  • Use a custom encoder: json.dumps(data, default=str)
python3 fixes

Asyncio timeout

asyncio\.exceptions\.TimeoutError|asyncio\.TimeoutError

  • Increase the timeout value in asyncio.wait_for() or aiohttp session
  • Add retry logic for transient network issues
python3 fixes

StopIteration — iterator exhausted

StopIteration

  • Use next(iterator, default_value) to provide a fallback
  • Wrap in try/except StopIteration or use a for loop instead