RE: unzip problem

2011-06-24 Thread steve+comp . lang . python
Ahmed, Shakir wrote:

> The problem is happening when it is coming to write option.
> 
> The * is not the real name of the zip file, I just hide the name.

Please don't waste our time by showing us fake code that doesn't do what you
say it does.

You said that "The script is here", but that was not true, was it? What you
showed us was not the script you were running. What other changes,
deliberate or accidental, did you make?

If you are going to edit the script to make it simpler (a good idea!),
please run it first to make sure you still get the same error.



-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Significant figures calculation

2011-06-24 Thread steve+comp . lang . python
Jerry Hill wrote:

> I'm curious.  Is there a way to get the number of significant digits
> for a particular Decimal instance?  I spent a few minutes browsing
> through the docs, and didn't see anything obvious.  I was thinking
> about setting the precision dynamically within a function, based on
> the significance of the inputs.

Not officially, so far as I know, but if you're willing to risk using a
private implementation detail that is subject to change:

>>> decimal.Decimal('000123.45000')._int
'12345000'

However, sometimes you may need to inspect the exponent as well:

>>> zero = decimal.Decimal('0.')
>>> zero._int
'0'
>>> zero._exp
-8



-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what's the big deal for print()

2011-06-24 Thread steve+comp . lang . python
John Gordon wrote:

> In 
> pipehappy  writes:
> 
>> Why people want print() instead of print str? That's not a big deal
>> and the old choice is more natural. Anyone has some clue?
> 
> Because the new Python uses print().  print "str" is the old way.


I think you missed the point of the question, which is, *why* does the new
Python (version 3+) use a function print() instead of a statement?

The problems with print as a statement includes:

It requires special treatment in the compiler, instead of just being an
ordinary function like len(), etc.

It's hard to come up with special syntax to add extra functionality to print
statement. Compare the ugly syntax needed to add support for printing to
writable files in Python 2:

print >>fileobj, arg  # what does the mysterious >> syntax mean?

compared to the natural way it works in Python 3:

print(arg, file=fileobj)

Likewise, changing the delimiter between arguments. Python 3 has:

>>> print(1, 2, 3, sep="*")
1*2*3

while Python 2 requires you to generate the string by hand, and then print
it:

>>> print '*'.join('%s' % x for x in (1, 2, 3))
1*2*3


One Frequently Asked Question is "How do I get rid of the newline after
printing?" In Python 2, you leave a comma at the end of the print
statement. What? A comma? How does that make *any* sense at all???
Unfortunately, while that gets rid of the newline, it also leaves spaces
between items:

>>> def example():
... print 1,
... print 2,
... print 3
...
>>> example()
1 2 3

Here's the Python 3 version:

>>> def example():
... print(1, sep='', end='')
... print(2, sep='', end='')
... print(3, sep='')
...
>>> example()
123


To get the same result in Python 2, you have to use sys.stdout.write().


The canonical explanation for why print is now a function is here:

http://www.python.org/dev/peps/pep-3105/




-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: those darn exceptions

2011-06-25 Thread steve+comp . lang . python
Chris Angelico wrote:

> On Sat, Jun 25, 2011 at 10:25 AM, Ben Finney 
> wrote:
>> No. The answer is *still* “why, any exception at all”. The name
>> ‘os.read’ could be re-bound at run-time to any object at all, so a code
>> checker that you “point at any given line of code” can't know what the
>> name will be bound to when that line gets executed.
> 
> Sure it can. And KeyboardInterrupt could be raised at any time, too.
> But this is a TOOL, not a deity. If Function X is known to call
> Function Y and built-in method Z, 

Known by whom? You? Me? The author of X, Y or Z? Everybody? The tool?

How is the tool supposed to know which functions are called? What if it
doesn't have access to the source code of Y? It might only be available via
a .pyc file, or it might be written in C, or Fortran, or Java (for Jython),
or C# (for IronPython).

Who is responsible for ensuring that every time the implementation of *any*
of X, Y and Z change, the list of exceptions is updated? What do you think
the chances are that this list will remain accurate after a few years of
maintenance?

Is this list of exceptions part of the API of function X? Should X be held
responsible if Z stops raising (say) AttributeError and starts raising
NameError instead?

Should the *implementation* of X, namely the fact that it calls Y and Z, now
considered part of the public interface?

These are serious questions, not nit-picks. Unless they can be answered
satisfactorily, this hypothetical tool *cannot exist*. It simply won't
work. I believe that you might as well be asking for a deity, because the
tool will need supernatural powers beyond the abilities of ordinary code.

And I haven't even raised the spectre of replacing functions (even builtins)
at runtime, or the use of eval/exec, or any number of other tricks.


> and also raises FooException, then 
> X's list of "most likely exceptions" would be FooException +
> Y.__exceptions__ + Z.__exceptions__. 

Even if you somehow, magically, know that X calls Y and Z, you can't draw
that conclusion. Lists of exceptions don't add like that. Consider:

def Y(a):
if a is None: raise ValueError
return a
Y.__exceptions__ = (ValueError,)

def X(a):
if a is None: raise TypeError
return Y(a)
X.__exceptions__ = (TypeError,)


You claim that X's "most likely exceptions" are given by X.__exceptions__ +
Y.__exceptions__. Under what circumstances do you think X could raise
ValueError?

For bonus points, identify the lies in the above code. (Hint: there are at
least two.)


> It won't be perfect, but it'd be 
> something that could go into an autodoc-style facility. Obviously you
> can fiddle with things, but in _ordinary usage_ this is what it's
> _most likely_ to produce.

All this will do is lull people into a false sense of security as they come
to rely on incorrect and out-of-date information. They'll still be in as
ignorant a position re exceptions as they are now, only they won't know it.


-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3 syntax error question

2011-06-26 Thread steve+comp . lang . python
rzed wrote:

> I've tried to install PySVG in a Python 3 setting, and I get a few
> errors on the build. Most are easy to fix, but this one I can't
> explain or fix:
> 
> 
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "builders.py", line 12, in 
> from pysvg.shape import *
>   File "C:\Python32\lib\site-packages\pysvg\shape.py", line 91
> def moveToPoint(self,(x,y)):
>  ^
> SyntaxError: invalid syntax
> 

Function signatures with automatic tuple-unpacking are no longer allowed in
Python3. So functions or methods like this:

def moveToPoint(self,(x,y)):

have to be re-written with the tuple unpacking moved into the body of the
function, e.g. something like this:

def moveToPoint(self, x_y):
x, y = x_y


Are you aware that you're trying to install a Python2 library under Python3?


-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: using an instance of Object as an empty class

2011-06-29 Thread steve+comp . lang . python
Ulrich Eckhardt wrote:

> Peter Otten wrote:
>> Examples for classes that don't accept attributes are builtins
>> like int, tuple, and -- obviously -- dict. You can make your own
>> using the __slot__ mechanism:
>> 
> class A(object):
>> ... __slots__ = ["x", "y"]
>> ...
> a = A()
> a.x = 42
> a.y = "yadda"
> a.z = 123
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> AttributeError: 'A' object has no attribute 'z'
> 
> Wow. This is something I've been missing dearly in my toolbox until now!
> Typically, when in C++ I would have used a struct, I always created a
> class that set the according attributes in the init function instead,
> which is quite a bit more cumbersome. Or I used a tuple and hoped to get
> the position of the elements correct.

Often, the right solution for that is to use collections.namedtuple:

>>> from collections import namedtuple as nt
>>> struct = nt('struct', 'x y z spam ham cheese')
>>> obj = struct(x=2, spam='tasty', y=3, z=0, cheese=None, ham='')
>>> obj
struct(x=2, y=3, z=0, spam='tasty', ham='', cheese=None)

namedtuple is available starting in Python 2.6.

This is not quite a struct, because it is immutable like all tuples. So
while you can access fields either by position or name:

>>> obj[1]
3
>>> obj.y
3

you can't modify them. This is usually a feature.

__slots__ are generally considered the wrong solution. They were added to
the language purely as an optimization for cases where you need huge
numbers of objects and the space required by all the instance.__dict__ was
prohibitive. Unfortunately, __slots__ don't play well with various other
aspects of Python (e.g. inheritance), see Christian's earlier post for more
details. But if you can live with the limits of __slots__, perhaps it will
work for you.


-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list


Safely modify a file in place -- am I doing it right?

2011-06-29 Thread steve+comp . lang . python
I have a script running under Python 2.5 that needs to modify files in
place. I want to do this with some level of assurance that I won't lose
data. E.g. this is not safe:

def unsafe_modify(filename):
fp = open(filename, 'r')
data = modify(fp.read())
fp.close()
fp = open(filename, 'w')  # <== original data lost here
fp.write(fp)
fp.close()  # <== new data not saved until here

If something goes wrong writing the new data, I've lost the previous
contents.

I have come up with this approach:

import os, tempfile
def safe_modify(filename):
fp = open(filename, 'r')
data = modify(fp.read())
fp.close()
# Use a temporary file.
loc = os.path.dirname(filename)
fd, tmpname = tempfile.mkstemp(dir=loc, text=True)
# In my real code, I need a proper Python file object, 
# not just a file descriptor.
outfile = os.fdopen(fd, 'w')
outfile.write(data)
outfile.close()
# Move the temp file over the original.
os.rename(tmpname, filename)

os.rename is an atomic operation, at least under Linux and Mac, so if the
move fails, the original file should be untouched.

This seems to work for me, but is this the right way to do it? Is there a
better/safer way?



-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list