Dereferencing a value before checking for None

Dereferencing a value before checking for None

Description

A request parameter retrieved with .get() may be None when it is absent. Calling a method on that value or calculating its length without checking it raises an exception.

Potential impact

  • Omitting a required parameter may cause service errors or denial of service.
  • Debug settings may expose internal information when the error occurs.

Remediation

  • Check the .get() result with is not None, or provide a suitable default before using it.
  • Declare required request values in the framework's validation layer.

Examples

These excerpts belong inside a request-handling function.

Before

python
filename = request.POST.get("filename")
return filename.count(".")

After

python
filename = request.POST.get("filename")
if filename is not None:
    return filename.count(".")
return 0

If filename is present, the example counts its dots. If the request omits it, the function returns 0.

References