How naive is Python?
Duncan Booth
duncan.booth at invalid.invalid
Mon Jan 15 03:47:22 EST 2007
More information about the Python-list mailing list
Mon Jan 15 03:47:22 EST 2007
- Previous message (by thread): How naive is Python?
- Next message (by thread): How naive is Python?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Roy Smith <roy at panix.com> wrote: > All of those just move around pointers to the same (interned) string. Correct about the pointers, but the string is not interned: Steven D'Aprano <steve at REMOVEME.cybersource.com.au> wrote: >>>> s1 = foo() >>>> s2 = foo() >>>> s1 == s2, s1 is s2 > (True, True) > > So the string "This is a test" within foo is not copied each time the > function is called. However, the string "This is a test" is duplicated > between foo and foo2 (the two functions don't share the same string > instance): > >>>> s3 = foo2() >>>> s3 == s1, s3 is s1 > (True, False) > In this specific example the two functions don't share the same string, but that won't always be the case: if the string had been interned this would have printed (True, True). e.g. Removing all the spaces from the string produces a string which is interned. >>> def foo(): s = "Thisisatest" return s >>> def foo2(): return "Thisisatest" >>> s1 = foo() >>> s2 = foo2() >>> s1 is s2 True Bottom line, never make assumptions about when two literal strings will share the same object and when they won't.
- Previous message (by thread): How naive is Python?
- Next message (by thread): How naive is Python?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list