Skip to content

remove calls to empty functions #741

Description

@vali-fake-account

Empty functions and a few very simple functions can always be replaced with the return value when used in an assignment (e.g. x = f()) or removed completely when acting as a procedural function call.

def f1(): ...
def f2(): pass
def f3(): return
def f4(): return None
def f5(): return 123
def f6(): return 60 * 60 * 24
def f7(hours=24):  # Replace/remove only when called without args: `f7()` 
    return 60 * 60 * hours

It might seem like no one would define empty functions, but I sometimes do the following to make debugging easier without adding vulnerabilities in production:

if __debug__:
    def f(): ... do something ...
else:
    def f(): pass

With this optimization, I could have the best of both worlds (easy debugging during development and zero added overhead to production).

I also use this pattern:

def f(data, cb: Callable = lambda *args: None):
    ...
    r = cb(data)
    ...

Instead of this:

def f(data, cb: Callable | None = None):
    ...
    if cb:
        r = cb(data)
    else: 
        r = None
    ...

The function def identity(x): return x can simplify the logic in some cases when I use functional programming. For example, when delegating which function should be passed to map() or filter().

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions