As far as I know, Python doesn’t support function overloading, but in Python documentation
seems that there are 2 different str methods, str(object='') and str(object=b'', encoding='utf-8', errors='strict')
How are defined these functions? When is the first invoked and when the second?
Can I create my own f(o='') and f(o=b'') functions (makes sense)?
UPDATE
Output for str(b'abc','utf-8') is abc but
output for str(b'abc') is b'abc'
No, python doesn’t support overloading because it doesn’t need to. Python documentation often shows different ways of calling a method to illustrate different uses, but there is only one
str()callable (a type in this case).In this case,
str()accepts multiple keyword arguments, which have default values if not specified. Thestr()type then uses the those extra keyword arguments, if specified, to interpret ab''byte string argument. If no keyword arguments were passed in,str()behaves differently.In other words,
str()adjusts it’s behaviour based on wether or not the keyword arguments have been supplied. If that is the case and the first argument is a bytestring or bytearray, it’ll decode that argument to unicode text, using the extra keyword arguments to control the decoding process.You can define your own function that’ll behave the same way as regards to the keyword arguments, checking the type of the first argument: