Editor

Run Once

#276 · Functions · Intermediate · 60 XP · about 10 min

Some work should happen only once: opening a connection, loading a big file, printing a welcome banner. Write a decorator run_once(func) that makes this automatic.

  • The first time the decorated function is called, it calls func with the given arguments and returns the result.
  • Every later call returns that same result without calling func again, whatever arguments it gets.
  • If the call to func raises an exception, the exception passes through and nothing is remembered, so the next call runs func again.

Any result counts, including None, 0 and False: once func has returned, it is never called again.

Examples

@run_once
def connect(host):
    print('connecting to', host)
    return 'session-' + host

connect('alpha')    # prints connecting to alpha, returns 'session-alpha'
connect('beta')     # prints nothing, returns 'session-alpha'

Constraints

  • Each decorated function has its own memory: decorating two functions gives two separate switches
  • Arguments can be positional or keyword arguments

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.