Ohgodmanyo
Ohgodmanyo

Reputation: 19

How would I read the outputs with angle brackets in python

Code example:

>>> class Snake:
        pass

and then I do this

>>> snake = Snake()
>>> print(snake)
<__main__.Snake object at 0x7f315c573550>

How can I test what this returns?

if snake == "<__main__.Snake object at 0x7f315c573550>":
    print("it worked")

the if statement does not work. how can I test what snake is equal to in an if statement? thanks.

Upvotes: 0

Views: 670

Answers (2)

wjandrea
wjandrea

Reputation: 33107

From the docs:

By default, object implements __eq__() by using is

So, if snake == snake, but that's a tautology.

I think what you actually want to do is check if snake is a Snake instance:

if isinstance(snake, Snake):

Upvotes: 3

tdelaney
tdelaney

Reputation: 77367

print displays the string representation of the object, not the object itself. In fact, the object itself is just a bunch of bits in memory, so what should it look like? In your case, you can get the same string representation and compare.

str(snake) == "<__main__.Snake object at 0x7f315c573550>":
    print("it worked")

Since the number at the end varies each time you create a Snake object, you could use a regex to match part of it while leaving details of that hex number to chance.

import re
if re.match(r"<__main__\.Snake object at 0x[\da-f]+>", str(snake)):
    print("it worked")

Upvotes: 0

Related Questions