tags:

views:

79

answers:

3

Is there a way to get object.__doc__ as a raw string, apart from adding an 'r' in-front of the doctring itself in the source code?

I have latex code inside and the '\r's, '\f's etc are creating problems.

+3  A: 

No, you have to add the r. If you don't add the r, there's no way you can be sure to get back the original string no matter what you do.

If you don't like raw strings the other alternative is to escape your backslashes in the strings with an extra backslash.

Mark Byers
+2  A: 

the difference between a raw string and otherwise is just a matter of source code literal syntax. once parsed, there is no 'raw' string object. the result of repr(object.__doc__) will always be such that you can copy and paste the result into a python source script and get the original string.

consider:

>>> def foo():
...     'foo\nbar'
...     pass
...
>>> foo.__doc__
'foo\nbar'
>>> print foo.__doc__
foo
bar
>>>
TokenMacGuy
Doesn't work for '\\d\d'
Mark Byers
@Mark Byers: `'\\d\d'` contains an invalid escape sequence. the string python stores is equivalent to `r'\d\d'`. specifically, when python reads the literal, it transforms the first escape to a single backslash, but the second escape is just kept untransformed. If you want to store the string `\\d\d` then you need to either use a raw string: `r'\\d\d'` or escape the string correctly yourself: `'\\\\d\\d'`
TokenMacGuy
+7  A: 

There's no such Python type as "raw string" -- there are raw string literals, which are just one syntax approach (out of many) to specify constants (i.e., literals) that are of string types. So "getting" something "as a raw string" just makes no sense. You can write docstrings as raw string literals (i.e., with the prefix r -- that's exactly what denotes a raw string literal, the specific syntax that identifies such a constant to the Python compiler), or else double up any backslashes in them (an alternative way to specify constant strings including backslash characters), but that has nothing to do with "getting" them one way or another.

Alex Martelli