1

I am studying the functools library in python. However, when I copy the examples from the documentation for the decorator

@singledispatch

I do not get the same results as the ones that are reported on the docs.

from functools import singledispatch

@singledispatch
def fun(arg, verbose=False):
    if verbose:
        print("Let me just say,", end=" ")
    print(arg)

@fun.register
def _(arg: int, verbose=False):
    if verbose:
        print("Strength in numbers, eh?", end=" ")
    print(arg)

@fun.register
def _(arg: list, verbose=False):
    if verbose:
        print("Enumerate this:")
    for i, elem in enumerate(arg):
        print(i, elem)

Should evaluate to:

>>> fun("Hello, world.")
Hello, world.
>>> fun("test.", verbose=True)
Let me just say, test.
>>> fun(42, verbose=True)
Strength in numbers, eh? 42
>>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)
Enumerate this:
0 spam
1 spam
2 eggs
3 spam

But in my juypter notebook it just doesn't.

>>> fun("Hello, world.")
Hello, world.
>>> fun("test.", verbose=True)
Let me just say, test.
>>> fun(42, verbose=True)
Let me just say, 42
>>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True)
Let me just say, ['spam', 'spam', 'eggs', 'spam']
TrebledJ
  • 8,713
  • 7
  • 26
  • 48
Tytire Recubans
  • 967
  • 10
  • 27

0 Answers0