1

If you define functions in Python, they need to have different names. Overloading functions is advised against by many people and only possible using extra packages and tricks.

Yet, there seems to be one glaring exception: the print function. It exists without any arguments (to print just a newline character), with one argument (to print that argument followed by a newline character) and has four other optional parameters.

How come such a thing even exists in Python?

How does it work in just the base installation?

Does this mean that one can overload functions (at least with optional arguments) without the need for extra packages?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
LukasFun
  • 171
  • 1
  • 4
  • 17
  • 4
    _Is_ that a glaring exception? Quite a few functions accept `*args` and/or `**kwargs`. It's not an _overload_, the one implementation just deals with whatever was passed to it. – jonrsharpe Jan 07 '22 at 17:25
  • default arguments. `def f(a=0, b= 1, c=2, d=4):pass`. You can call `f()`, `f(99)`, `f(99, 100)`, `f(99, 100, 101)`, and `f(99, 100, 101, 102)`. – Ch3steR Jan 07 '22 at 17:26
  • 3
    print function signature [`print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)`](https://docs.python.org/3/library/functions.html#print) `*args` can accept 0 or more arguments. – Ch3steR Jan 07 '22 at 17:28
  • 2
    If you want to talk about exceptions, `slice` and `range` are far more "glaring", in that they treat the positional arguments differently based on how many there are. – chepner Jan 07 '22 at 17:31
  • `print` isn't exceptional: it prints its arguments, however many there may be, separated by its `sep` keyword argument and terminated by the `end` keyword argument. – chepner Jan 07 '22 at 17:32
  • Python has several features (most from the very earliest days of the language) that seem to come from a "do as I say, not as I do" mindset. – chepner Jan 07 '22 at 17:33
  • Others (like positional-only parameters) were originally only available to functions implemented in C, but were later added to the langauge itself. – chepner Jan 07 '22 at 17:36

0 Answers0