python.lang.maintainability.return.return-not-in-function

profile photo of semgrepsemgrep
Author
6,393
Download Count*

return only makes sense inside a function

Run Locally

Run in CI

Defintion

rules:
  - id: return-not-in-function
    patterns:
      - pattern-not-inside: |
          def $F(...):
              ...
          # TODO: first pattern should just automatically include this one
      - pattern-not-inside: |
          def $F(...) ->  $Y:
              ...
      - pattern: return ...
    message: "`return` only makes sense inside a function"
    languages:
      - python
    severity: WARNING
    metadata:
      category: maintainability
      technology:
        - python
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

return.py



def alwaysblue():
    if isblue():
        return 'blue'
    # ruleid: code-after-unconditional-return
    return 'red'
    return 'green'


def alwaysblue():
    if isblue():
        return 'blue'
    # ruleid: code-after-unconditional-return
    return 'red'
    x = 5


def resolve(key: str):
    key = os.path.join(path, "keys", key)
    # ok: code-after-unconditional-return
    return key


def resolve(key: str) -> str:
    key = os.path.join(path, "keys", key)
    # ok: code-after-unconditional-return
    return key

def resolve(key: str) -> str:
    key = os.path.join(path, "keys", key)
    # ok: code-after-unconditional-return
    return key, key

# ruleid: return-not-in-function
return (a, b)