Possible to change a function’s repr in python?

Yes, if you’re willing to forgo the function actually being a function. First, define a class for our new type: import functools class reprwrapper(object): def __init__(self, repr, func): self._repr = repr self._func = func functools.update_wrapper(self, func) def __call__(self, *args, **kw): return self._func(*args, **kw) def __repr__(self): return self._repr(self._func) Add in a decorator function: def withrepr(reprfun): def … Read more

What is the meaning of %r?

Background: In Python, there are two builtin functions for turning an object into a string: str vs. repr. str is supposed to be a friendly, human readable string. repr is supposed to include detailed information about an object’s contents (sometimes, they’ll return the same thing, such as for integers). By convention, if there’s a Python … Read more

Understanding repr( ) function in Python

>>> x = ‘foo’ >>> x ‘foo’ So the name x is attached to ‘foo’ string. When you call for example repr(x) the interpreter puts ‘foo’ instead of x and then calls repr(‘foo’). >>> repr(x) “‘foo'” >>> x.__repr__() “‘foo'” repr actually calls a magic method __repr__ of x, which gives the string containing the representation … Read more

Why do backslashes appear twice?

What you are seeing is the representation of my_string created by its __repr__() method. If you print it, you can see that you’ve actually got single backslashes, just as you intended: >>> print(my_string) why\does\it\happen? The string below has three characters in it, not four: >>> ‘a\\b’ ‘a\\b’ >>> len(‘a\\b’) 3 You can get the standard … Read more