1
zoo.py
from main import animal

def getAnimal(animal)
    1) if animal == animal.tiger:
    or
    2) if animal == "animal"     

and

main.py
import Zoo        
Class animal
    tiger = "tiger"
    bear  = "bear"

1) get = Zoo.getAnimal(animal.tiger)
or
2) get = Zoo.getAnimal("tiger"):

The above is extremely basic example but what is the "best" convention of performing the above code?

I was told it is better to do it via 1) approach because "strange things happen due to how python uses pointers."

Whats happening in terms of at memory level when the above codes are executed?

If I remember correctly, each memory addr gets ascii value of char for the conseq allocated memory address for strings?

Is it the same when string is now being referenced as an object that of animal.tiger?

Or are there no differences at all?

1 Answer 1

2

If the compiler doesn't optimize the code (i.e. it's more complex than your example) #2 will allocate an anonymous string with another pointer.

But since == do string compare it will work even if it is two different strings (in memory).

In your example the compiler will most likely optimize the code to be the same:

>>> class animal:
...  tiger = "tiger"
...  bear = "bear"
...
>>> animal.tiger
'tiger'
>>> id(animal.tiger)
140052399801616
>>> id('tiger')
140052399801616
>>>

EDIT: Added example of user input where string memory location differ:

>>> id(animal.tiger)
140052399801616
>>> a=raw_input()
tiger
>>> id(a)
140052399801664
>>> a==animal.tiger
True
>>> a is animal.tiger
False

(use is to compare objects in memory as above)

Sign up to request clarification or add additional context in comments.

4 Comments

Normally, they will actually be the same as they are both constant interned strings. However, if you got the input e.g. from a user, they would not be the same object.
@nneonneo what do you mean by having an input from user being a diff object?
@ealeon: See Qiau's edit. Basically, dynamically-generated strings will generally have memory addresses separate from constant (interned) strings, at least in CPython (the most popular implementation).
so the answer is there is no difference?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.