Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Location of python string class in the source code

Tags:

I'm looking into overloading the + operator for a certain string so I was thinking of subclassing the string class then adding the code in the new class. However I wanted to take a look at the standard string class first but I can't seem to find it... stupid eh?

Can anyone point the way? Even online documentation of the source code.

like image 718
momo Avatar asked Sep 29 '10 09:09

momo


People also ask

Where is Python source code?

The source for python 2.7 itself can be found at http://hg.python.org/cpython. Other versions of python have had their source imported onto Launchpad. You can see them here. Click on one you want to see and you can then click "Browse the Code".

Is there a string class in Python?

Python has a built-in string class named "str" with many handy features (there is an older module named "string" which you should not use). String literals can be enclosed by either double or single quotes, although single quotes are more commonly used.

How do I see the class code in Python?

We use the getsource() method of inspect module to get the source code of the function. Returns the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string.


2 Answers

It's documented here. The main implementation is in Objects/stringobject.c. Subclassing str probably isn't what you want, though. I would tend to prefer composition here; have an object with a string field, and special behavior.

like image 197
Matthew Flaschen Avatar answered Jan 01 '23 20:01

Matthew Flaschen


You might mean this.

class MyCharacter( object ):     def __init__( self, aString ):         self.value= ord(aString[0])     def __add__( self, other ):         return MyCharacter( chr(self.value + other) )     def __str__( self ):         return chr( self.value ) 

It works like this.

>>> c= MyCharacter( "ABC" ) >>> str(c+2) 'C' >>> str(c+3) 'D' >>> c= c+1 >>> str(c) 'B' 
like image 23
S.Lott Avatar answered Jan 01 '23 21:01

S.Lott