Skip to content

Instantly share code, notes, and snippets.

@addcninblue
Last active March 12, 2022 02:21
Show Gist options
  • Save addcninblue/a2d81c5238e0732f776690a7254646fc to your computer and use it in GitHub Desktop.
Save addcninblue/a2d81c5238e0732f776690a7254646fc to your computer and use it in GitHub Desktop.

Explanation for str, repr, and the REPL:

You can memorize these two rules, and everything will be merry and well.

Rule 1:

When you see

>>> EXPR

you can think of this as doing exactly the following (for the purposes of 61A):

if EXPR is not None:
    print(repr(EXPR))

Examples:

>>> class A:
>>>     def __repr__(self):
>>>        return "A"
>>> A()     # print(repr(A()))
A
>>> repr(A())    # print(repr(repr(A())))
'A'

Rule 2:

When you see

print(EXPR)

you can think of this as doing exactly the following:

  1. thing_to_output = str(EXPR)
  2. cut off the quotes in thing_to_output, and print that to the terminal.

Examples:

>>> print("hi") # 1: "hi"; 2: chop off quotes, so we get just hi
hi
>>> print(A()) # 1. str defaults to repr, so we get "A"; 2: chop off quotes, so we get just A
A

Note for the curious (out of scope for 61A)!

For the built-in str, __str__ returns itself __repr__ returns an extra set of quotes around itself.

Examples:

>>> str("a string")
'a string'
>>> repr("a string")
"'a string'"
```py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment