{"record":{"id":"470cbc4b025cde1a","repo":"microsoft/aspire","slug":"cannot-use-none-in-reference-expression","errorCode":null,"errorMessage":"Cannot use None in reference expression","messagePattern":"Cannot use None in reference expression","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"src/Aspire.Hosting.CodeGeneration.Python/PythonModuleBuilder.cs","lineNumber":1434,"sourceCode":"                        result[\"$expr\"][\"valueProviders\"] = self._value_providers\n                    return result\n                raise ValueError(\"Invalid ReferenceExpression: must have either handle, condition, or format\")\n\n            def __repr__(self) -> str:\n                if self._handle:\n                    return f\"ReferenceExpression(handle={self._handle.handle_id})\"\n                if self._condition:\n                    return \"ReferenceExpression(conditional)\"\n                return f\"ReferenceExpression(formattedString)\"\n\n\n        def _extract_handle_for_expr(value: typing.Any) -> typing.Any:\n            '''\n            Extracts a value for use in reference expressions.\n            Supports handles (objects) and string literals.\n            '''\n            if value is None:\n                raise ValueError(\"Cannot use None in reference expression\")\n\n            # String literals - include directly in the expression\n            if isinstance(value, str):\n                return value\n\n            # Number literals - convert to string\n            if isinstance(value, (int, float)):\n                return str(value)\n\n            # Handle objects - get their JSON representation\n            if isinstance(value, (Handle, _ReferenceHandle)):\n                return value\n\n            # Objects with $handle property (already in handle format)\n            if isinstance(value, dict) and \"$handle\" in value:\n                return value\n\n            raise ValueError(","sourceCodeStart":1416,"sourceCodeEnd":1452,"githubUrl":"https://github.com/microsoft/aspire/blob/25830f84bd145686607ad00c057b3f84e2e51d43/src/Aspire.Hosting.CodeGeneration.Python/PythonModuleBuilder.cs#L1416-L1452","documentation":"_extract_handle_for_expr raises ValueError('Cannot use None in reference expression') when a None value is passed where a reference-expression operand is expected. Reference expressions accept handles, string literals, or numbers; None is not a valid operand because it cannot be serialized into an expression value.","triggerScenarios":"Passing None as an argument to a reference-expression builder (e.g., string_expr-style composition or an API that extracts handles from values) — typically from an unassigned variable or an optional field left unset.","commonSituations":"A resource/endpoint lookup returned None and the result was fed into an expression; optional kwargs defaulted to None and were passed through; refactored code where a variable lost its assignment; reading config values that are missing and come back None.","solutions":["Ensure the value is resolved before building the expression; fail fast if a required resource handle is None.","Substitute an explicit string literal (e.g., empty string or a default) when None is legitimately possible.","Use conditional logic to skip the expression entirely when the value is absent.","Check that the upstream lookup (handle acquisition) actually succeeded before composing the expression."],"exampleFix":"// before\nhandle = find_resource(name)  # may be None\nexpr = string_expr(\"{h}\", h=handle)\n// after\nhandle = find_resource(name)\nif handle is None:\n    raise ValueError(f\"resource {name!r} not found\")\nexpr = string_expr(\"{h}\", h=handle)","handlingStrategy":"validation","validationCode":"def operand_or_fail(value):\n    if value is None:\n        raise ValueError('reference-expression operand was None; resolve resource first')\n    return value","typeGuard":"def is_valid_operand(value) -> bool:\n    return value is not None and (isinstance(value, (str, int, float)) or hasattr(value, 'handle_id'))","tryCatchPattern":"try:\n    expr = string_expr('{h}', h=value)\nexcept ValueError as e:\n    if 'Cannot use None' in str(e):\n        expr = string_expr('{h}', h='')\n    else:\n        raise","preventionTips":["Check handle-producing lookups for None before composing expressions","Substitute explicit defaults for optional values","Fail fast with your own error when a required resource is missing"],"tags":["python","reference-expression","null","validation"],"backgroundTag":"null-argument","analyzedSha":"25830f84bd145686607ad00c057b3f84e2e51d43","analyzedAt":"2026-09-16T11:10:06.193Z","contentChangedAt":"2026-09-16T11:10:06.193Z","schemaVersion":2},"datasetVersion":"2026-09-21T09:17:21.228Z"}