Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could one write a function in python to replace the current str() function?

I know how to cast to a string, but how does casting to a string actually work? Like if I were to write my own function in python to replace the current str() function how would I do that?

like image 512
Alex Rowe Avatar asked Mar 17 '26 14:03

Alex Rowe


1 Answers

str as a type

You cannot replace the str type. It is a base type which cannot be mimicked with a Python class without using str itself.

In the same way, you could not write an int class without using int as it is your builtin way to represent cardinal values.

This happens because Python is a high-level language. You can think of it as an API for using a lot of well-crafted C functions, in the case of CPython. This means you do not have access to key components such as pointers, bit manipulation and memory allocation that would allow you to reimplement some types such as int, str or tuple without somehow using them in the process.

str cast

At a more basic level, if what you want is to know how the piping for casting to a string works, it is relatively straightforward.

The function str will call the __str__ method of the object to cast. If it does not exist, it falls back on repr.

def str(obj=''):
    if hasattr(obj, '__str__'):
        return obj.__str__()
    else:
        return repr(obj)

It is the responsibility of the object to format a str to be returned by its __str__ method.

like image 158
Olivier Melançon Avatar answered Mar 20 '26 05:03

Olivier Melançon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!