[Tutor] Puzzled again
Steven D'Aprano
steve at pearwood.info
Wed Aug 3 10:45:40 CEST 2011
Richard D. Moores wrote:
> Puzzled again. Why the error. Line 36 is the line just above "import
> os.path". I have many other functions in mycalc.py with examples
> formatted exactly the same way.
>
> def convertPath(path):
> """
> Given a path with backslashes, return that path with forward slashes.
>
> By Steven D'Aprano 07/31/2011 on Tutor list
> >>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
Are you aware that this is not a raw string? It's wrapped inside another
non-raw string, so it is merely a sub-string containing the letters r
single-quote C colon backslash-U etc. Now, as it turns out, backslash-U
and friends don't have any special meanings, so it will work fine, but
that's an accident of the characters in the path. If it were backslash-n
(say) instead, things would be different.
(P.S. the docstring itself can be a raw string. Just start it with r"""
instead of """.)
> >>> convertPath(path)
> 'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'
> """
> import os.path
> separator = os.path.sep
> if separator != '/':
> path = path.replace(os.path.sep, '/')
> return path
>
>>>> from mycalc import convertPath
> Traceback (most recent call last):
> File "<string>", line 36, in <fragment>
> Syntax Error: """: c:\Python32\lib\site-packages\mycalc.py, line 36-1
Is this the actual traceback you received? I would expect that importing
mycalc.py would be fine, but that trying to run doctest over it *may*
play up, probably with a SyntaxError.
It works fine for me when I paste your code directly into an interactive
session, and the docstring looks as expected:
>>> print(convertPath.__doc__)
Given a path with backslashes, return that path with forward slashes.
By Steven D'Aprano 07/31/2011 on Tutor list
>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
>>> convertPath(path)
'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'
In general, expect to have fun and games getting doctests to do the
right thing with backslashes. The interaction of doctests (which uses
exec under the hood) and backslashes is rather ugly. But I don't know if
that's the problem here.
Other than that, I'm afraid I can't reproduce your error. Perhaps there
is some invisible character in the original file, such as a DOS "End of
File" ctrl-Z, which was messing things up for you, you've eventually,
and accidentally, deleted it. Because there's nothing obvious to explain
why you get the error you get, or why it goes away when it does.
--
Steven
More information about the Tutor
mailing list