[Tutor] Doubts galore.

Lie Ryan lie.1296 at gmail.com
Thu Jun 10 17:41:11 CEST 2010


On 06/11/10 01:14, prasad rao wrote:
> Hi
> 
> def cript(doc=None,data =None):
>    if  doc==None and data==None:doc=sys.agv1
>    elif doc:
>         data=open(doc,'r').read()
>         data_c= binascii.hexlify(data)
>    else:data_c= binascii.hexlify(data)
>    if doc:
>         q=tempfile.TemporaryFile()
>         q.write(data_c)
>         os.rename(q,doc)
>         return
>    return data_c
> 
> 
> cript(doc='./language.txt')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 10, in cript
> TypeError: coercing to Unicode: need string or buffer, file found
> 
> 1)Why I got the above error message with  the above function?How to correct it?

The error message points out here:

# line 10
        os.rename(q,doc)
                 ^^^

scanning a few lines earlier, we saw:

        q=tempfile.TemporaryFile()

os.rename() doesn't rename a file object; os.rename() takes two string
arguments.


> 2)Is it reasonable to have 2 if blocks in a function as above?

This is where boolean algebra can help. An elif-block will only be run
when all the if-elif blocks before it evaluates to false. IOW, your code
is equivalent to this:

   if doc==None and data==None: doc=sys.agv1
   if not (doc==None and data==None) and doc:
        data=open(doc,'r').read()
        data_c= binascii.hexlify(data)

except that "doc==None and data==None" is only evaluated once.

So, using boolean algebra (assuming a reasonable definition of == and !=):

not (doc==None and data==None) and doc
(doc!=None or data!=None) and doc

now depending on the intent of "doc" and "doc != None"; it may be
possible to simplify that to only: data != None.

Note that this is all assuming a reasonable definition of ==, !=, not,
etc and assuming no side effects and assuming that the checks are
equally lightweight.

> 3)Dose the tempfile create a fileobject on harddisk or in memory(Dose it save my
>   file as I expect it to do)

AFAIK, tempfile creates a file in harddisk, but I've never used
tempfile, so don't quote me on that.



More information about the Tutor mailing list