*tuple vs tuple example print os.path.join(os.path.dirname(os.tmpnam()),*("a","b","c"))

S

Steve

I have been trying to find documentation on the behavior
Can anyone tell me why the first example works and the second doesn't
and where I can read about it in the language reference?
Steve

print os.path.join(os.path.dirname(os.tmpnam()),*("a","b","c"))
#works
OUTPUT:/var/tmp/a/b/c
and

print os.path.join(os.path.dirname(os.tmpnam()),("a","b","c")) #
doesn't
OUTPUT:Traceback (most recent call last):
File "<stdin>", line 1, in ?
File
"/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/posixpath.py",
line 60, in join
if b.startswith('/'):
AttributeError: 'tuple' object has no attribute 'startswith'
 
F

Fredrik Lundh

Steve said:
I have been trying to find documentation on the behavior

the behaviour of what ?
Can anyone tell me why the first example works and the second doesn't
and where I can read about it in the language reference?

the os.path.join documentation (in the library reference) says

join(path1[, path2[, ...]])

Joins one or more path components intelligently. /.../ The return
value is the concatenation of path1, and optionally path2, etc.,
with exactly one directory separator (os.sep) inserted between
components /.../

that is, the syntax is

path = os.path.join("part1", "part2", "part3")

your first example
print os.path.join(os.path.dirname(os.tmpnam()),*("a","b","c"))

is equivalent to

print os.path.join(os.path.dirname(os.tmpnam()), "a", "b", "c")

which matches the description in the library reference.

the "*" notation is described, among other places, in the "calls"
section of the language reference:

http://docs.python.org/ref/calls.html

"If the syntax "*expression" appears in the function call,
"expression" must evaluate to a sequence. Elements from
this sequence are treated as if they were additional
positional arguments"


you second example
print os.path.join(os.path.dirname(os.tmpnam()),("a","b","c")) #

passes in a tuple as path2, which doesn't match the library reference.
since Python expects you to pass in a string, you get an exception when
you pass in something else.

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,699
Latest member
AnneRosen

Latest Threads

Top