Re: Preventing execution of a method

2008-12-12 Thread Bruno Desthuilliers

Emanuele D'Arrigo a écrit :

On Dec 11, 7:48 pm, Bruno Desthuilliers
 wrote:

or to provide read-only
access. I.e. right now I'm working on the graphical client which
potentially could be rewritten entirely by the users. It is necessary
and perfectly reasonable for the client module to access some of the
objects to be represented graphically, but those objects shouldn't be
modifiable by it.

Why so ? At worst, they'll break everything.


-IF- the application was single-user yes, it wouldn't be a big deal.
But as it is potentially multi-user, I don't want one party to corrupt
the application for everybody else.


A multi-users application with a GUI usually implies that it's a 
client-server app with the GUI deployed is on each client and the domain 
logic hosted on the server.

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


Re: [Python.NET] Where does the clr in IronPython look the dll

2008-12-12 Thread Craig Farrow


The dll needs to be on the Python path (sys.path). You can either add to
the path with sys.path.append("c:\") or put your dll in a folder in
the Python site-packages directory and add a .pth file (for Python.NET, 
but not IronPython

 -- it doesn't recognise the .pth files).

Regards,

Craig.

3/12/2008 9:20 p.m. dï, navneet khanna wrote:

Hello Everybody

I am trying to import dll with clr.AddReference("TCdll")
I am getting the following error.

Traceback (most recent call last):
  File "", line 1, in 
clr.AddReference("TCdll")
FileNotFoundException: Unable to find assembly 'TCdll'.
   at Python.Runtime.CLRModule.AddReference(String name)

I have loaded the dll in system32 folder. Have I loaded the dll at the 
right place or do I need to place it anywhere else?

Waiting for your replies.

Regards
Navneet


_
Python.NET mailing list - pythondot...@python.org
http://mail.python.org/mailman/listinfo/pythondotnet



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


Removing None objects from a sequence

2008-12-12 Thread Filip Gruszczyński
Hi!

I would like to iterate over a sequence nad ignore all None objects.
The most obvious way is explicitly checking if element is not None,
but it takes too much space. And I would like to get something faster.
I can use
[ sth for sth in self.__sth if not sth is None ], but I don't know if
that's the best way. I checked itertools, but the only thing that
seemed ok, was ifilter - this requires seperate function though, so
doesn't seem too short. How can I get it the shortest and fastest way?

-- 
Filip Gruszczyński
--
http://mail.python.org/mailman/listinfo/python-list


Re: Removing None objects from a sequence

2008-12-12 Thread Erik Max Francis

Filip Gruszczyński wrote:


I would like to iterate over a sequence nad ignore all None objects.
The most obvious way is explicitly checking if element is not None,
but it takes too much space.


That doesn't make much sense; why would iterating over the sequence take 
more _space_?


--
Erik Max Francis && m...@alcyone.com && http://www.alcyone.com/max/
 San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
  Life is a gamble so I should / Live life more carefully
   -- TLC
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is slow

2008-12-12 Thread Marco Mariani

Giampaolo Rodola' wrote:


The real (and still unsolved) problem with PyPy is the installation
which requires something like a dozen of third-party packages to be
installed.
Unfortunately it seems there are no plans yet for releasing any
Windows/Linux/Mac installer in the near future.


I'm not using it, but at least Ubuntu 8.10 has the .deb packages of pypy 
1.0. And I remember installing a release last year in a few minutes, 
during a conference talk.

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


Re: Moving to subprocess from os.popen--pipe closes prematurely

2008-12-12 Thread Martin P. Hellwig

Kevin Walzer wrote:

Hello,

I'm trying to move from os.popen to using subprocess, and I'm having 
trouble with the pipe suddenly closing.


My old code looked something like this:




Hi Kevin,

You could try something more like:
>>> import subprocess
>>> cmd = subprocess.Popen([executable_path, executable_options], 
stdout=subprocess.PIPE, stdout=subprocess.PIPE)

>>> std_out, std_err = cmd.communicate(standard_in_value)

std_out is a string though, you probably need to split it on newline to 
get the same sort of list and since it is buffered in memory you 
probably don't want to use .communicate if you expect megabytes of data 
back.


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


Re: Removing None objects from a sequence

2008-12-12 Thread alex23
On Dec 12, 7:18 pm, "Filip Gruszczyński"  wrote:
> Hi!
>
> I would like to iterate over a sequence nad ignore all None objects.
> The most obvious way is explicitly checking if element is not None,
> but it takes too much space. And I would like to get something faster.
> I can use
> [ sth for sth in self.__sth if not sth is None ], but I don't know if
> that's the best way. I checked itertools, but the only thing that
> seemed ok, was ifilter - this requires seperate function though, so
> doesn't seem too short. How can I get it the shortest and fastest way?

Rather than a list comprehension, use a generator expression:

for item in (x for x in sequence if x is not None):
   do_something(x)

This doesn't generate the intermediate list with None elements
removed, rather it steps one at a time through the original sequence
and only returns the non-None elements.
--
http://mail.python.org/mailman/listinfo/python-list


File names, character sets and Unicode

2008-12-12 Thread Michal Ludvig
Hi all,

is there any way to determine what's the charset of filenames returned
by os.walk()?

The trouble is, if I pass  argument to os.walk() I get the
filenames as byte-strings. Possibly UTF-8 encoded Unicode, who knows.

OTOH If I pass  to os.walk() all the filenames I get in
the loop are already unicode()d.

However with some locales settings os.walk() dies with for example:
Traceback (most recent call last):
  File "tst.py", line 10, in 
for root, dirs, files in filelist:
  File "/usr/lib/python2.5/os.py", line 303, in walk
for x in walk(path, topdown, onerror):
  File "/usr/lib/python2.5/os.py", line 293, in walk
if isdir(join(top, name)):
  File "/usr/lib/python2.5/posixpath.py", line 65, in join
path += '/' + b
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1:
ordinal not in range(128)

I can't even skip over these files with 'os.walk(..., onerror=handler)'
the handler() is never called.

That happens for instance when the file names have some non-ascii
characters and locales are set to ascii, but reportedly in some other
cases as well.

What's the right and safe way to walk the filesystem and get some
meaningful filenames?


Related question - if the directory is given name on a command line
what's the right way to preprocess the argument before passing it down
to os.walk()?

For instance with LANG=en_NZ.UTF-8 (i.e. UTF-8 system):
* directory is called 'smile☺'
* sys.argv[1] will be 'smile\xe2\x98\xba' (type str)
* after .decode("utf-8") I get u'smile\u263a' (type unicode)

But how should I decode() it when running on a system where $LANG
doesn't end with "UTF-8"? Apparently some locales have non-ascii default
charsets. For instance zh_TW is BIG5 charset by default, ru_RU is
ISO-8850-5, etc. How do I detect that to get the right charset for decode()?

I tend to have everything internally in Unicode but it's often unclear
how to convert some inputs to Unicode in the first place. What are the
best practices for dealing with these chraset issues in Python?

Thanks!

Michal
--
* Amazon S3 backup tool -- http://s3tools.logix.cz/s3cmd



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


Re: File names, character sets and Unicode

2008-12-12 Thread Marc 'BlackJack' Rintsch
On Fri, 12 Dec 2008 23:32:27 +1300, Michal Ludvig wrote:

> is there any way to determine what's the charset of filenames returned
> by os.walk()?

No.  Especially under *nix file systems file names are just a string of 
bytes, not characters.  It is possible to have file names in different 
encondings in the same directory.

> The trouble is, if I pass  argument to os.walk() I get the
> filenames as byte-strings. Possibly UTF-8 encoded Unicode, who knows.

Nobody knows.  :-)

> What's the right and safe way to walk the filesystem and get some
> meaningful filenames?

The safe way is to use `str`.

> Related question - if the directory is given name on a command line
> what's the right way to preprocess the argument before passing it down
> to os.walk()?

Pass it as is.

> For instance with LANG=en_NZ.UTF-8 (i.e. UTF-8 system): * directory is
> called 'smile☺'
> * sys.argv[1] will be 'smile\xe2\x98\xba' (type str) * after
> .decode("utf-8") I get u'smile\u263a' (type unicode)
> 
> But how should I decode() it when running on a system where $LANG
> doesn't end with "UTF-8"? Apparently some locales have non-ascii default
> charsets. For instance zh_TW is BIG5 charset by default, ru_RU is
> ISO-8850-5, etc. How do I detect that to get the right charset for
> decode()?

You can't.  Even if you know the preferred encoding of the system, e.g. 
via $LANG, there is no guarantee that all file names are encoded this way.

> I tend to have everything internally in Unicode but it's often unclear
> how to convert some inputs to Unicode in the first place. What are the
> best practices for dealing with these chraset issues in Python?

I'm usually using UTF-8 as default but offer the user ways, e.g. command 
line switches, to change that.

If I have to display file names in a GUI I use a decoded version of the 
byte string file name, but keep the byte string for operations on the 
file.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Removing None objects from a sequence

2008-12-12 Thread Filip Gruszczyński
I don't mean memory, but space in code ;-)

I'll try this generator :)

-- 
Filip Gruszczyński
--
http://mail.python.org/mailman/listinfo/python-list


Building extensions for python 2.6 adm64 with the SDK compiler

2008-12-12 Thread David Cournapeau
Hi,

I have some trouble building python 2.6 extensions with the SDK
compiler on windows 64 bits. The problem is that after link step,
mt.exe is called to embed the MANIFEST into the executable, but the
manifest is not created, so the build fails with a "general error
c1010070:Failed to load and parse the manifest". I am a bit confused:
 - I thought that manifest should not be embedded in .pyd
(http://bugs.python.org/issue4120), but the code of msvc9compiler.py
in distutils suggests otherwise, and uses the option /MANIFESTFILE
(which only changes the name of the manifest, according to MSDN).
 - Is this specific to the SDK compiler ? E.g. does the native VS
compiler on 64 bits have the same problem ? I guess not, because
people would have complained before, I guess.

If I manually add the /MANIFEST file to the link options, the build does work,

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


Re: Removing None objects from a sequence

2008-12-12 Thread Tim Rowe
2008/12/12 Filip Gruszczyński :
> I don't mean memory, but space in code ;-)

Trying to save printer paper for your listings, then?

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


(Very Newbie) Problems defining a variable

2008-12-12 Thread febaen
#!/usr/bin/python
#Py3k, UTF-8

bank = int(input("How much money is in your account?\n>>"))
target = int(input("How much money would you like to earn each year?
\n>>"))

interest = 0
i = 0

while interest < target:
#determine the interest rate to use
if bank >= :
rate = 0.006
elif bank >= 1 and bank <= 24999:
rate = 0.0085
elif bank >= 25000 and bank <= 4:
rate = 0.0124
elif bank >= 5 and bank <= 9:
rate = 0.0149
elif bank >= 10:
rate = 0.0173
#Now that we know what interest rate to use, apply it...
lastbank = bank#To calculate interest...
bank += (bank * rate)  #Update earnings...
interest = bank - lastbank #And figure out how much interest is made!
i += 1  #So we can see which year a calculation represents
print("Year %s, at %s rate: %s paid, %s in bank." % (i, rate,
interest, bank))



I wrote this expanding off an 'interest' exercise in a tutorial, which
was fairly simple (assume %1, calculate for ten years). It's intended
to take how much the user has in the bank and determine how long it
will be until it generates a certain amount in interest each year. The
problem is that rates are not solid, and increase at certain points. I
put the rates from the basic account option at my bank in as an
example.

I'm pretty certain that that is also the problem in the code. I'm
pretty sure it's a problem with the 'if' statements', and it looks
like it's one of those mistakes that's so simple you look back on it
and laugh at yourself. If you put in a bank number <= , it fails,
saying  "NameError: name 'rate' is not defined". If you put in one
higher, it runs correctly, but thinks that the rate is 0.006

I tried def'ing a function for it, which didn't work any better. I'm
having a hard time figuring out exactly why it is those if statements
are wrong.
--
http://mail.python.org/mailman/listinfo/python-list


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread feba
On Dec 12, 5:56 am, Bruno Desthuilliers  wrote:
> feb...@gmail.com a écrit :
>
>
>
> > #!/usr/bin/python
> > #Py3k, UTF-8
>
> > bank = int(input("How much money is in your account?\n>>"))
> > target = int(input("How much money would you like to earn each year?
> > \n>>"))
>
> > interest = 0
> > i = 0
>
> > while interest < target:
> > #determine the interest rate to use
> >    if bank >= :
> >            rate = 0.006
> >    elif bank >= 1 and bank <= 24999:
> >            rate = 0.0085
> >    elif bank >= 25000 and bank <= 4:
> >            rate = 0.0124
> >    elif bank >= 5 and bank <= 9:
> >            rate = 0.0149
> >    elif bank >= 10:
> >            rate = 0.0173
>
> (snip)
>
> > I'm pretty certain that that is also the problem in the code. I'm
> > pretty sure it's a problem with the 'if' statements', and it looks
> > like it's one of those mistakes that's so simple you look back on it
> > and laugh at yourself. If you put in a bank number <= , it fails,
> > saying  "NameError: name 'rate' is not defined".  If you put in one
> > higher, it runs correctly, but thinks that the rate is 0.006
>
> Indeed. That's what you asked for. If bank is >= , then rate will be
> set to 0.006, and the following tests will be skipped. Else - since you
> just don't handle the case -, rate is not defined at all.
>
> I guess you wanted your first test to be:
>
>     if bank <= :
>        ...
>
> FWIW, when using if/elif that way, make sure you always end with a
> "default" else clause (even if just to signal you didn't expect to be
> there...)
>
> HTH


that's it, thanks! was confused with it being basically in a column of
all >= *.

I replaced it with

if bank <= 0:
print("You're in the red!")
quit()
elif bank >= 1 and bank <= :
rate = 0.0060
elif bank >= 1 and bank <= 24999:
rate = 0.0085
elif bank >= 25000 and bank <= 4:
rate = 0.0124
elif bank >= 5 and bank <= 9:
rate = 0.0149
elif bank >= 10:
rate = 0.0173
else:
print("What's this doing here?")

which also changes it to keep it from going on forever if you put in a
negative amount. Out of curiosity, would you still recommend applying
an 'else' clause in this case? I don't see how it could ever be
triggered, even if there's an error of some kind
--
http://mail.python.org/mailman/listinfo/python-list


How to write binary data to file and socket

2008-12-12 Thread Lee Soin
Hello, all!
I'm new to python. In Linux C programming, writing data to file and socket
share the same system call "write". But it seems that only data of string
type can be used for "write" and "send". So how to write binary data to file
and socket?

-- 
Sun Li
Department of Physics
Nanjing University, China
--
http://mail.python.org/mailman/listinfo/python-list


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Steven D'Aprano
On Fri, 12 Dec 2008 04:05:21 -0800, feba wrote:

> that's it, thanks! was confused with it being basically in a column of
> all >= *.
> 
> I replaced it with
> 
>   if bank <= 0:
>   print("You're in the red!")
>   quit()
>   elif bank >= 1 and bank <= :
>   rate = 0.0060

You can replace this with the simpler, easier to read and faster:

elif 1 <= bank <= :
rate = 0.0060
elif 1 <= bank <= 24999:
rate = 0.0085

...

>   elif bank >= 10:
>   rate = 0.0173
>   else:
>   print("What's this doing here?")

Change the last two else clauses to this one:

else:
rate = 0.0173



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


Re: Removing None objects from a sequence

2008-12-12 Thread Steven D'Aprano
On Fri, 12 Dec 2008 10:18:35 +0100, Filip Gruszczyński
wrote:

> Hi!
> 
> I would like to iterate over a sequence nad ignore all None objects. The
> most obvious way is explicitly checking if element is not None, but it
> takes too much space.

Too much space???

seq = [x for x in seq if x is not None]

It's one line, less than 40 characters. If your hard disk is so full that 
you're worrying about 40 characters, I suggest you need a bigger disk.


> And I would like to get something faster.

Faster than what? What speed do we have to beat? 


> I can use
> [ sth for sth in self.__sth if not sth is None ], but I don't know if
> that's the best way. 

Who cares if it's the "best" way? What's important is, is it good enough?

It is easier to optimize correct code than to correct optimized code. Get 
your code working first, then worry about shaving microseconds off the 
runtime *if you need to*.


> I checked itertools, but the only thing that seemed
> ok, was ifilter - this requires seperate function though, so doesn't
> seem too short. How can I get it the shortest and fastest way?

You could do this:

seq = filter(None, seq)

but only if you know that seq doesn't contain any false objects other 
than None.


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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Chris Rebert
On Fri, Dec 12, 2008 at 3:42 AM,   wrote:
> #!/usr/bin/python
> #Py3k, UTF-8
>

>
> #determine the interest rate to use
>if bank >= :
>rate = 0.006
>elif bank >= 1 and bank <= 24999:
>rate = 0.0085
>elif bank >= 25000 and bank <= 4:
>rate = 0.0124
>elif bank >= 5 and bank <= 9:
>rate = 0.0149
>elif bank >= 10:
>rate = 0.0173

For the love of Benji, reverse the ordering of the clauses so you
don't have to keep checking whether the number is also under the next
limit!
(I'm assuming Bruno's guess about your first test having the operator
flipped around the wrong way was right)

if bank >= 10:
rate = 0.0173
elif bank >= 5:
rate = 0.0149
elif bank >= 25000:
rate = 0.0124
elif bank >= 1:
rate = 0.0085
else:
rate = 0.006

Note how much simpler that is to read and understand. And switching
the default case to the 'else' is just idiomatic.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


IF YOU WANT TO LIVE LONGER, YOU SHOULD CHECK THIS!!

2008-12-12 Thread andrew
http://www.associatedcontent.com/article/995306/parameningeal_infection_brain_abscess.html?cat=70
--
http://mail.python.org/mailman/listinfo/python-list


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread bearophileHUGS
feba:
>         if bank <= 0:
>                 print("You're in the red!")
>                 quit()
>         elif bank >= 1 and bank <= :
>                 rate = 0.0060
>         elif bank >= 1 and bank <= 24999:
>                 rate = 0.0085
>         elif bank >= 25000 and bank <= 4:
>                 rate = 0.0124
>         elif bank >= 5 and bank <= 9:
>                 rate = 0.0149
>         elif bank >= 10:
>                 rate = 0.0173
>         else:
>                 print("What's this doing here?")

I think your indents are a little too much large (the soft standard is
4 spaces).

The last else can be removed.

Does bank == 0 mean being in red?

That list of if-elif seems bug-prone. In the future you will learn
ways to write that in a less bug-prone (but also probably more complex
to read and understand) way.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Bruno Desthuilliers

feb...@gmail.com a écrit :

#!/usr/bin/python
#Py3k, UTF-8

bank = int(input("How much money is in your account?\n>>"))
target = int(input("How much money would you like to earn each year?
\n>>"))

interest = 0
i = 0

while interest < target:
#determine the interest rate to use
if bank >= :
rate = 0.006
elif bank >= 1 and bank <= 24999:
rate = 0.0085
elif bank >= 25000 and bank <= 4:
rate = 0.0124
elif bank >= 5 and bank <= 9:
rate = 0.0149
elif bank >= 10:
rate = 0.0173


(snip)


I'm pretty certain that that is also the problem in the code. I'm
pretty sure it's a problem with the 'if' statements', and it looks
like it's one of those mistakes that's so simple you look back on it
and laugh at yourself. If you put in a bank number <= , it fails,
saying  "NameError: name 'rate' is not defined".  If you put in one
higher, it runs correctly, but thinks that the rate is 0.006


Indeed. That's what you asked for. If bank is >= , then rate will be 
set to 0.006, and the following tests will be skipped. Else - since you 
just don't handle the case -, rate is not defined at all.


I guess you wanted your first test to be:

   if bank <= :
  ...

FWIW, when using if/elif that way, make sure you always end with a 
"default" else clause (even if just to signal you didn't expect to be 
there...)


HTH


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


Re: var or inout parm?

2008-12-12 Thread Chris Rebert
On Fri, Dec 12, 2008 at 4:34 AM, sturlamolden  wrote:

> You cannot modify parameters by rebinding. x = x + 1 is a rebinding. x
> += 1 is not.

Python begs to differ, as those two statements are both semantically
identical in this case:

Python 2.6 (r26:66714, Nov 18 2008, 21:48:52)
[GCC 4.0.1 (Apple Inc. build 5484)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 2
>>> id (x)
8405372
>>> x += 1
>>> id(x)
8405360
>>> x = x + 1
>>> id(x)
8405348

If you were talking about lists rather than integers though, you'd be
absolutely correct, as the += ends up being a method call to __iadd__
instead of a plain assignment.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I manually uninstall setuptools (installed by egg)?

2008-12-12 Thread David Cournapeau
On Thu, Dec 11, 2008 at 10:30 PM, Nick Craig-Wood  wrote:
> David Cournapeau  wrote:
>>  On Wed, Dec 10, 2008 at 12:04 PM, Chris Rebert  wrote:
>> > On Tue, Dec 9, 2008 at 6:49 PM,   wrote:
>> >> On Ubuntu, I accidentally manually installed setuptools
>> >> http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file
>> >> as a shell script via sudo), and now realize I should just be using
>> >> apt to take care of my system Python packages.
>> >
>> > Really, why? setuptools has more Python packages/programs available
>> > and updates faster than Debian.
>> > It's also likely that some of the Debian Python packages are installed
>> > using setuptools anyway.
>> > So, why do you think apt and not setuptools is The Right Way(tm)?
>>
>>  Setuptools is certainly not the right way to install packages
>>  system-wide on debian, it is very likely to break the whole thing.
>
> It wouldn't be too difficult to make a .deb target which would collect
> all the files that did get installed into a package.  It would be a
> rather rough and ready package but would do the job.

Depends what you mean by would do the job: rather rough certainly does
not mean "would do the job" for something as essential as a package
IMO.

>
> The .deb would then be uninstallable in the usual (dpkg --purge) way.
>
> Did anyone think about that?

Yes, there is stddeb which does that (make a .deb package from a
setuptools package).


>
> easy_install can do that I think...

Not without a lot of hoola, unfortunately; for example, it breaks
stow, so I have to use specialy scripts to circumvent the damn thing
and make it what I tell him to do. I never understood what's easy
about easy install: it is broken in so many ways, and has caused me so
many pains - even when I was not using - that I do not trust it at
all. I only use it to download packages (and even then it manage to
fail more than work), and always install them from setup.py afterwards
(at which step I of course also have to circumvent setuptools if the
package uses setuptools).

cheers,

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


Imaging library in jython

2008-12-12 Thread whiter4bbit
Hi,

Is there any ways to use python Imaging library in jython?
--
http://mail.python.org/mailman/listinfo/python-list


Re: var or inout parm?

2008-12-12 Thread sturlamolden
On Dec 7, 9:54 am, m...@pixar.com wrote:

> How can I make a "var" parm, where the called function can modify
> the value of the parameter in the caller?
>
> def f(x):
> x = x + 1

Short ansver:

You can modify function parameters if they are mutable. If they are
immutable any attempt to modify the parameter will trigger a copy.

You cannot modify parameters by rebinding. x = x + 1 is a rebinding. x
+= 1 is not.

If you need to modify immutable parameters or do the modification by
rebinding, pass the variable back. Python allows multiple return
values.
















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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Bruno Desthuilliers

feba a écrit :

On Dec 12, 5:56 am, Bruno Desthuilliers  wrote:

(snip)

I guess you wanted your first test to be:

if bank <= :
   ...

(snip)

that's it, thanks! was confused with it being basically in a column of
all >= *.

I replaced it with

if bank <= 0:
print("You're in the red!")
quit()
elif bank >= 1 and bank <= :
rate = 0.0060
elif bank >= 1 and bank <= 24999:
rate = 0.0085
elif bank >= 25000 and bank <= 4:
rate = 0.0124
elif bank >= 5 and bank <= 9:
rate = 0.0149
elif bank >= 10:
rate = 0.0173
else:
print("What's this doing here?")

which also changes it to keep it from going on forever if you put in a
negative amount.


Good point.


Out of curiosity, would you still recommend applying
an 'else' clause in this case?


Yes, but I'd use it as a replacement for the last test:

# code here ...
elif bank >= 5 and bank <= 9:
rate = 0.0149
else:
rate = 0.0173


And finally, I'd simplify the whole damn thing:

if bank < 1:
print("You're in the red!")
quit()
elif bank < 1:
rate = 0.0060
elif bank < 25000:
rate = 0.0085
elif bank < 5:
rate = 0.0124
elif bank < 10:
rate = 0.0149
else:
rate = 0.0173


I don't see how it could ever be
triggered, even if there's an error of some kind


It couldn't, indeed. Which FWIW is a clear indication that the previous 
test ( elif bank >= 10:) is redundant !-)


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


Re: var or inout parm?

2008-12-12 Thread sturlamolden
On Dec 12, 1:44 pm, "Chris Rebert"  wrote:

> Python begs to differ, as those two statements are both semantically
> identical in this case:

That is because integers are immutable. When x += 1 is done on an int,
there will be a rebinding. But try the same on say, a numpy array, and
the result will be different:

>>> import numpy
>>> x = numpy.zeros(10)
>>> id(x)
19504848
>>> x += 1
>>> id(x)
19504848
>>> x = x + 1
>>> id(x)
10451488


Whereas:

>>> x = 1
>>> id(x)
10051256
>>> x += 1
>>> id(x)
10051244
>>> x = x + 1
>>> id(x)
10051232




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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread feba
Actually, I have gedit set to four spaces per tab. I have no reason
why it's showing up that large on copy/paste, but the file itself is
fine.

Thanks for the advice Chris, Stephen, I can definitely see how those
are both far better ways of doing it. I have it as:

#!/usr/bin/python
#Py3k, UTF-8

bank = int(input("How much money is in your account?\n>>"))
if bank <=0:
print("You need a postive amount to gain interest.")
quit()
target = int(input("How much money would you like to earn each year?
\n>>"))

interest = 0
i = 0

while interest < target:
#determine the interest rate to use
if bank >= 10:
rate = 0.0173
elif bank >= 5:
rate = 0.0149
elif bank >= 25000:
rate = 0.0124
elif bank >= 1:
rate = 0.0085
else:
rate = 0.0060
#Now that we know what interest rate to use, apply it...
lastbank = bank#To calculate interest...
bank += (bank * rate)  #Update earnings...
interest = bank - lastbank #And figure out how much interest is made!
i += 1  #So we can see which year a calculation represents
print("Year %s, at %s rate: %s paid, %s in bank." % (i, rate,
interest, bank))

now it checks to make sure the account is positive before moving on,
in addition to using your recommendations on readability and
efficiency in getting the rate


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


Re: var or inout parm?

2008-12-12 Thread sturlamolden
On Dec 12, 1:56 pm, sturlamolden  wrote:

> That is because integers are immutable. When x += 1 is done on an int,
> there will be a rebinding. But try the same on say, a numpy array, and
> the result will be different:


And a consequence of this is, if you have a function like

def foobar(x):
   x += 1

then the parameter x will be modified given that x have mutable type.

However, if we have a function like

def foobar(x):
   x = x + 1

then x will not be modified, mutable or not.

(Well, you could abuse operator overlaoding to make unexpected side
effects in the latter case. But except for such insanity it will not
have side-effects.)








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


Re: Removing None objects from a sequence

2008-12-12 Thread Filip Gruszczyński
I am not doing it, because I need it. I can as well use "if not elem
is None", but I just wanted to know, if there is some better way of
doing this. I like to know :-)

And I can't understand why you are becoming so aggressive because of
this. Just because I asked for that, doesn't mean, that I will put
some obfuscated code into my project. I just wanted to learn something
new - I checked itertools, I googled a bit, now I wanted to ask here
if someone knew some really cool way of this.  All the other
assumptions weren't really necessary.

Thanks for those ideas, however. I like the last one a lot :)

-- 
Filip Gruszczyński
--
http://mail.python.org/mailman/listinfo/python-list


Re: File names, character sets and Unicode

2008-12-12 Thread Steve Holden
Michal Ludvig wrote:
> Hi all,
> 
> is there any way to determine what's the charset of filenames returned
> by os.walk()?
> 
> The trouble is, if I pass  argument to os.walk() I get the
> filenames as byte-strings. Possibly UTF-8 encoded Unicode, who knows.
> 
> OTOH If I pass  to os.walk() all the filenames I get in
> the loop are already unicode()d.
> 
> However with some locales settings os.walk() dies with for example:
> Traceback (most recent call last):
>   File "tst.py", line 10, in 
> for root, dirs, files in filelist:
>   File "/usr/lib/python2.5/os.py", line 303, in walk
> for x in walk(path, topdown, onerror):
>   File "/usr/lib/python2.5/os.py", line 293, in walk
> if isdir(join(top, name)):
>   File "/usr/lib/python2.5/posixpath.py", line 65, in join
> path += '/' + b
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1:
> ordinal not in range(128)
> 
> I can't even skip over these files with 'os.walk(..., onerror=handler)'
> the handler() is never called.
> 
> That happens for instance when the file names have some non-ascii
> characters and locales are set to ascii, but reportedly in some other
> cases as well.
> 
> What's the right and safe way to walk the filesystem and get some
> meaningful filenames?
> 
> 
> Related question - if the directory is given name on a command line
> what's the right way to preprocess the argument before passing it down
> to os.walk()?
> 
> For instance with LANG=en_NZ.UTF-8 (i.e. UTF-8 system):
> * directory is called 'smile☺'
> * sys.argv[1] will be 'smile\xe2\x98\xba' (type str)
> * after .decode("utf-8") I get u'smile\u263a' (type unicode)
> 
> But how should I decode() it when running on a system where $LANG
> doesn't end with "UTF-8"? Apparently some locales have non-ascii default
> charsets. For instance zh_TW is BIG5 charset by default, ru_RU is
> ISO-8850-5, etc. How do I detect that to get the right charset for decode()?
> 
> I tend to have everything internally in Unicode but it's often unclear
> how to convert some inputs to Unicode in the first place. What are the
> best practices for dealing with these chraset issues in Python?
> 
There's currently a huge thread on python-dev dealing with (or rather
discussing) this very tortuous issue. Look for "Python-3.0, unicode, and
os.environ" in the archives. (The same issue, by the way, also applies
to environment variables).

In a nutshell, this is likely to cause pain until all file systems are
standardized on a particular encoding of Unicode. Probably only about
another fifteen years to go ...

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: How to write binary data to file and socket

2008-12-12 Thread Steve Holden
Lee Soin wrote:
> Hello, all!
> I'm new to python. In Linux C programming, writing data to file and
> socket share the same system call "write". But it seems that only data
> of string type can be used for "write" and "send". So how to write
> binary data to file and socket?
> 
Assuming you are using Python 2.x, use the struct module to convert your
data to a string, then write that.

In Python 3.x you would use the bytes type.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Python is slow

2008-12-12 Thread sturlamolden
On Dec 11, 4:25 am, Carl Banks  wrote:

> cm_gui is TROLL.  And I am not compring it with bots like Aaron
> Castironpi Brody.  cm_gui is even troller than Xah Lee!

Sure he is a troll, but he also have a point. Python is slower than it
needs to be.

Creating a fast implementation of a dynamic language is almost rocket
science. But it has been done. There is Stronghold, the fastest
version of Smalltalk known to man, on which the Sun Java VM is based.
On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3 And
most of that magic comes from an implementation of a dynamically typed
language (Smalltalk). A Python interpreter based on Strontalk would be
interesting...

http://shootout.alioth.debian.org/u32q/benchmark.php?test=all&lang=all

Second, there are other fast implementations of dynamic languages. The
CMUCL and SBCL versions of Common Lisp comes to min; you can see how
SBCL does in the same benchmark (CMUCL tends to be even faster).

So Python is a lot slower than it needs to be. But in most cases,
perceived 'slowness' comes from bad programming.

http://www.strongtalk.org/






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


Re: Removing None objects from a sequence

2008-12-12 Thread Steve Holden
Filip Gruszczyński wrote:
> Hi!
> 
> I would like to iterate over a sequence nad ignore all None objects.
> The most obvious way is explicitly checking if element is not None,
> but it takes too much space. And I would like to get something faster.
> I can use
> [ sth for sth in self.__sth if not sth is None ], but I don't know if
> that's the best way. I checked itertools, but the only thing that
> seemed ok, was ifilter - this requires seperate function though, so
> doesn't seem too short. How can I get it the shortest and fastest way?
> 
The problem with the list comprehension you quote above is that it
creates a new list, which costs both time and memory. You might want to
try using a generator expression instead:

(sth for sth in self.__sth if not sth is None)

This will give you the same sequence of values, but will produce them
only as they need to be consumed, saving the memory and compute overhead
of creating a second list.

>>> lst = [1, None, 3, None, "five", None]
>>> mylst = [l for l in lst if l is not None]
>>> mygen = (l for l in lst if l is not None)
>>> mylst, mygen
([1, 3, 'five'], )
>>> for l in mylst: print l,
...
1 3 five
>>> for l in mygen: print l,
...
1 3 five
>>>

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: var or inout parm?

2008-12-12 Thread Hrvoje Niksic
sturlamolden  writes:

> On Dec 12, 1:44 pm, "Chris Rebert"  wrote:
>
>> Python begs to differ, as those two statements are both semantically
>> identical in this case:
>
> That is because integers are immutable. When x += 1 is done on an int,
> there will be a rebinding. But try the same on say, a numpy array, and
> the result will be different:

The result will be different, but a still occurs!  You usually don't
notice it because augmented assignments with side effect are normally
careful to return the same object, so rebinding is a no-op.  But in
some cases, that can byte you.  For example, tupleobj[0] += 1 raises
an exception even when tupleobj[0] is mutable.  Taking the numpy
example:

>>> import numpy
>>> t = (numpy.zeros(10),)
>>> t
(array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]),)
>>> t[0] += 1
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment

Of course, the side effect occurs before the exception, so:

>>> t[0]
array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])
--
http://mail.python.org/mailman/listinfo/python-list


Re: var or inout parm?

2008-12-12 Thread sturlamolden
On Dec 12, 2:34 pm, Hrvoje Niksic  wrote:

> >>> import numpy
> >>> t = (numpy.zeros(10),)
> >>> t
>
> (array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]),)>>> t[0] += 1
>
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'tuple' object does not support item assignment
>
> Of course, the side effect occurs before the exception, so:
>
> >>> t[0]

> array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])


Actually I would consider this to be a bug. The tuple is immutable,
but no mutation of the tuple is ever attempted.

Sturla Molden



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


Re: Python is slow

2008-12-12 Thread sturlamolden
On Dec 12, 2:29 pm, sturlamolden  wrote:

> Creating a fast implementation of a dynamic language is almost rocket
> science. But it has been done. There is Stronghold,

I meant of course Strongtalk...
--
http://mail.python.org/mailman/listinfo/python-list


Interface & Implementation

2008-12-12 Thread J Ramesh Kumar
Hi, 

I am new to python. I require some help on implementing interface and its 
implementation. I could not find any sample code in the web. Can you please 
send me some sample code which is similar to the below java code ? Thanks in 
advance for your help.


public interface MyIfc
{
public void myMeth1();
public void myMeth2();
}

public class MyClass implements MyIfc
{
  public void myMeth1()
  {
  //do some implementation
  }

 public void myMeth2()
   {
   //do some implementation
   }
}
...

MyClass myc=new MyClass();
Hashtable hash=new Hashtable();
hash.put("MYIFC",myc);

MyIfc myi=(MyIfc)hash.get("MYIFC");
myi.myMeth1();
myi.myMeth2();
.

Thanks,
Ramesh--
http://mail.python.org/mailman/listinfo/python-list


Re: var or inout parm?

2008-12-12 Thread Steve Holden
sturlamolden wrote:
> On Dec 12, 1:56 pm, sturlamolden  wrote:
> 
>> That is because integers are immutable. When x += 1 is done on an int,
>> there will be a rebinding. But try the same on say, a numpy array, and
>> the result will be different:
> 
> 
> And a consequence of this is, if you have a function like
> 
> def foobar(x):
>x += 1
> 
> then the parameter x will be modified given that x have mutable type.
> 
> However, if we have a function like
> 
> def foobar(x):
>x = x + 1
> 
> then x will not be modified, mutable or not.
> 
> (Well, you could abuse operator overlaoding to make unexpected side
> effects in the latter case. But except for such insanity it will not
> have side-effects.)
> 
This was all thrashed out exhaustively in the still-feared call
semantics thread. Yes, augmented operations work differently on mutable
and immutable objects. Nothing to see here, move right along ...

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Marc 'BlackJack' Rintsch
On Fri, 12 Dec 2008 04:58:36 -0800, feba wrote:

> Actually, I have gedit set to four spaces per tab. I have no reason why
> it's showing up that large on copy/paste, but the file itself is fine.

The file contains one tab character per indentation level and it depends 
on the software you use to look at the text how many spaces will be 
displayed.  Better use four real spaces to indent one level so it looks 
the same everywhere.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is slow

2008-12-12 Thread Luis M . González
On Dec 12, 10:43 am, sturlamolden  wrote:
> On Dec 12, 2:29 pm, sturlamolden  wrote:
>
> > Creating a fast implementation of a dynamic language is almost rocket
> > science. But it has been done. There is Stronghold,
>
> I meant of course Strongtalk...

Blah, blah, blah...
Why don't you guys google a little bit to know what's being done to
address python's "slowness"??
It has been mentioned in this thread the pypy project (isn't it enough
for you??)
Other hints: shedskin, psyco, pyrex...
--
http://mail.python.org/mailman/listinfo/python-list


Re: var or inout parm?

2008-12-12 Thread Marc 'BlackJack' Rintsch
On Fri, 12 Dec 2008 05:39:35 -0800, sturlamolden wrote:

> On Dec 12, 2:34 pm, Hrvoje Niksic  wrote:
> 
>> >>> import numpy
>> >>> t = (numpy.zeros(10),)
>> >>> t
>>
>> (array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]),)>>> t[0] +=
>> 1
>>
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> TypeError: 'tuple' object does not support item assignment
>>
>> Of course, the side effect occurs before the exception, so:
>>
>> >>> t[0]
> 
>> array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])
> 
> 
> Actually I would consider this to be a bug. The tuple is immutable, but
> no mutation of the tuple is ever attempted.

No bug because a mutation *is* attempted.  ``a += x`` calls `a.__iadd__` 
which *always* returns the result which is *always* rebound to the name 
`a`.  Even with mutable objects where `__iadd__()` simply returns 
`self`!  It has to be this way because the compiler has no idea if the 
object bound to `a` will be mutable or immutable when the code actually 
runs.

In [252]: def f(a, x):
   .: a += x
   .:

In [253]: dis.dis(f)
  2   0 LOAD_FAST0 (a)
  3 LOAD_FAST1 (x)
  6 INPLACE_ADD
  7 STORE_FAST   0 (a)
 10 LOAD_CONST   0 (None)
 13 RETURN_VALUE

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: var or inout parm?

2008-12-12 Thread Hrvoje Niksic
sturlamolden  writes:

> Actually I would consider this to be a bug. The tuple is immutable,
> but no mutation of the tuple is ever attempted.

That's a common misconception about how += works in Python.  It simply
*always* rebinds.  Once you grok that, everything else follows.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is slow

2008-12-12 Thread sturlamolden
On Dec 12, 3:04 pm, Luis M. González  wrote:

> Why don't you guys google a little bit to know what's being done to
> address python's "slowness"??

Nothing is being done, and woth Py3k it got even worse.


> It has been mentioned in this thread the pypy project (isn't it enough
> for you??)
> Other hints: shedskin, psyco, pyrex...

None of those projects addresses inefficacies in the CPython
interpreter, except for psyco - which died of an overdose PyPy.

PyPy is interesting if they ever will be able to produce something
useful. They have yet to prove that. Even if PyPy can come up with a
Python JIT, they will still be decades behind the technologies of
Strongtalk and Java. That is the problem with reinventing the wheel
all over again.

Not to forget LLVM and Parrot which also will support Python
frontends.












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


Re: Python is slow

2008-12-12 Thread David Cournapeau
On Fri, Dec 12, 2008 at 11:04 PM, Luis M. González  wrote:

> It has been mentioned in this thread the pypy project (isn't it enough
> for you??)

Since pypy can't be used today for most production use (most python
packages can't work on it), I don't see how it could be enough for
anyone interested in solving problems today. I want faster function
calls to use with numpy: do you know of any solution ? Pypy certainly
isn't, at least today.

cheers,

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


Reading online zip files - zipfile and zlib, wbits

2008-12-12 Thread Brendan
I am fooling around with accessing contents of zip files online. I
download the tail end of the zip and use zipfile to get the zip
central directory structure. I download the section of the zip file I
need, directly read the zip file headers and use that information with
zlib to uncompress the data. The files I am examining will always be
compressed using deflate, with a wbits value of -15(minus for
headerless data because I am unsure whether the zip file header is
what zlib expects).

I can not find anywhere in the PK Zip Application notes (
http://www.pkware.com/documents/casestudies/APPNOTE.TXT ) how to
determine the value I should uze for wbits with zlib.decompress. I
have determined it is -15 from experimentation. Does anyone know the
answer to this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: var or inout parm?

2008-12-12 Thread sturlamolden
On Dec 12, 3:08 pm, Marc 'BlackJack' Rintsch  wrote:

> No bug because a mutation *is* attempted.  ``a += x`` calls `a.__iadd__`
> which *always* returns the result which is *always* rebound to the name
> `a`.  Even with mutable objects where `__iadd__()` simply returns
> `self`!

No, a mutation is not attempted, even if __iadd__() always returns a
value. If a rebinding of a member to the same member is attempted, the
tuple should not raise an exception. The tuple should check that it is
actually being *mutated* before it raises any exception. There is an
attempted write to the tuple, but not an attempted mutation of the
tuple. The tuple should tell the difference. Immutability does not
imply inwriteability, if the write operation changes nothing. But the
tuple raises an exception on any write attempt.














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


Re: Python is slow

2008-12-12 Thread sturlamolden
On Dec 12, 3:27 pm, "David Cournapeau"  wrote:

> I want faster function
> calls to use with numpy: do you know of any solution ? Pypy certainly
> isn't, at least today.

An interesting thing for numpy would be to use CUDA. If we can move
floating point ops to the GPU, a common desktop computer could yield
teraflops. A subclass of ndarray could be written for the nvidia GPU.

Using OpenMP within NumPy would also be interesting. There are desktop
computers available today with two quadcore processors.

There is multiprocessing, which works nicely with numpy. You can even
have multiple processes working on ndarrys that point to the same
shared memory. Just allocate a multiprocessing.Array and use its
buffer to create ndarray views.




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


Re: Python is slow

2008-12-12 Thread Stefan Behnel
David Cournapeau wrote:
> I want faster function
> calls to use with numpy: do you know of any solution ?

http://cython.org/

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


Re: Reading online zip files - zipfile and zlib, wbits

2008-12-12 Thread Brendan
On Dec 12, 10:25 am, Brendan  wrote:
> I am fooling around with accessing contents of zip files online. I
> download the tail end of the zip and use zipfile to get the zip
> central directory structure. I download the section of the zip file I
> need, directly read the zip file headers and use that information with
> zlib to uncompress the data. The files I am examining will always be
> compressed using deflate, with a wbits value of -15(minus for
> headerless data because I am unsure whether the zip file header is
> what zlib expects).
>
> I can not find anywhere in the PK Zip Application notes 
> (http://www.pkware.com/documents/casestudies/APPNOTE.TXT) how to
> determine the value I should uze for wbits with zlib.decompress. I
> have determined it is -15 from experimentation. Does anyone know the
> answer to this?

Okay, I found part of the answer here in the zip app notes
[quote]
general purpose bit flag: (2 bytes)

  Bit 0: If set, indicates that the file is encrypted.

  (For Method 6 - Imploding)
  Bit 1: If the compression method used was type 6,
 Imploding, then this bit, if set, indicates
 an 8K sliding dictionary was used.  If clear,
 then a 4K sliding dictionary was used.
  Bit 2: If the compression method used was type 6,
 Imploding, then this bit, if set, indicates
 3 Shannon-Fano trees were used to encode the
 sliding dictionary output.  If clear, then 2
 Shannon-Fano trees were used.

  (For Methods 8 and 9 - Deflating)
  Bit 2  Bit 1
0  0Normal (-en) compression option was used.
0  1Maximum (-exx/-ex) compression option was
used.
1  0Fast (-ef) compression option was used.
1  1Super Fast (-es) compression option was used.
[/quote]

Now I just don't understand Why Normal deflate corresponds to 15
wbits, and why I have to use headerless for the data, i.e. wbits = -15.
--
http://mail.python.org/mailman/listinfo/python-list


Re: var or inout parm?

2008-12-12 Thread Steve Holden
sturlamolden wrote:
> On Dec 12, 3:08 pm, Marc 'BlackJack' Rintsch  wrote:
> 
>> No bug because a mutation *is* attempted.  ``a += x`` calls `a.__iadd__`
>> which *always* returns the result which is *always* rebound to the name
>> `a`.  Even with mutable objects where `__iadd__()` simply returns
>> `self`!
> 
> No, a mutation is not attempted, even if __iadd__() always returns a
> value. If a rebinding of a member to the same member is attempted, the
> tuple should not raise an exception. The tuple should check that it is
> actually being *mutated* before it raises any exception. There is an
> attempted write to the tuple, but not an attempted mutation of the
> tuple. The tuple should tell the difference. Immutability does not
> imply inwriteability, if the write operation changes nothing. But the
> tuple raises an exception on any write attempt.
> 
OK, so if you regard the current behavior as a bug explain how to modify
the tuple's __iadd__ method and the coding of the INPLACE_ADD operator.
At least in pseudocode.

Criticism is easy. Now demonstrate that it's *informed* criticism.
Enough of the "should". I am always suspicious of suggestions that say
what the interpreter "should" or "should not" do. It makes it sound as
though you can wave a magic wand to achieve the desired behavior.

The interpreter "should not" have a GIL. The tuple "should" check that
it is actually being mutated. How?

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Python is slow

2008-12-12 Thread sturlamolden
On Dec 12, 3:43 pm, Stefan Behnel  wrote:

> http://cython.org/

How is the numpy support in Cython going? It was supposed to know
about ndarrays natively. I.e. not treat them as Python objects, but
rather as known C structs. That way an operation like arr[n] would not
result in a callback to Python, but translate directly to fast pointer
arithmetics.

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


Re: var or inout parm?

2008-12-12 Thread Hrvoje Niksic
sturlamolden  writes:

> On Dec 12, 3:08 pm, Marc 'BlackJack' Rintsch  wrote:
>
>> No bug because a mutation *is* attempted.  ``a += x`` calls `a.__iadd__`
>> which *always* returns the result which is *always* rebound to the name
>> `a`.  Even with mutable objects where `__iadd__()` simply returns
>> `self`!
>
> No, a mutation is not attempted, even if __iadd__() always returns a
> value.

Mutation is attempted.  A += x (where "A" could be anything valid at
the left-hand side of assignment, including item subscript) is not
implemented intuitivaly, as:

if hasattr(b, '__iadd__'):
A.__iadd__(x)   # ignore return value
else:
A = A.__add__(x)

It is implemented as something like:

if hasattr(b, '__iadd__'):
newval = A.__iadd__(x)
else:
newval = A.__add__(x)
A = newval

So the only difference between __add__ and __iadd__ is that __iadd__
is only consulted on +=, where as __add__ is consulted on both + and
+= (in the latter case only if __iadd__ is missing).

> The tuple should check that it is
> actually being *mutated* before it raises any exception.

Tuple has no way to check that.  What tuple sees is only the last
line:

t[0] = newval

At that point, the information about what is really going on is long
lost.  The only thing tuple could do is detect that the same object is
being written that's already there, but tuple doesn't do that by
design.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is slow

2008-12-12 Thread bearophileHUGS
sturlamolden:
> On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3 And
> most of that magic comes from an implementation of a dynamically typed
> language (Smalltalk). [...]
> http://shootout.alioth.debian.org/u32q/benchmark.php?test=all〈=all

That is indeed a nice result, JavaVM has come a long way from the
first one used for applets. That result comes mostly from the fact
that this is a test on a 4-core CPU, that is less easy to manage from
C. You can see that in the single 64-bit core tests:
http://shootout.alioth.debian.org/u64/benchmark.php?test=all&lang=all
And take a look at the memory used too, up to 34 times higher for the
JVM on the 4-core CPU.

In the next years people that use low-level languages like C may need
to invent a new language fitter for multi-core CPUs, able to be used
on GPUs too (see the OpenCL), less error-prone than C, able to use the
CPU vector instructions efficiently. (The D language is probably unfit
for this purpose, because even if it's meant to be a system language,
I don't think it can be used much to replace C everywhere it's used
now.) A C+ maybe? :-)

I agree that CPython may quite enjoy having something built-in like
Psyco, but it's a lot of work for an open source project. Probably
with 1/3 or 1/2 of the work poured on PyPy you may create that
improvement for CPython. Maybe PyPy will someday produce some fruit,
but I think they have used the wrong strategy: instead of trying to
create something very new that someday will work, it's often better to
try to improve something that today everybody uses, AND try to be
useful from almost the very beginning.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is slow

2008-12-12 Thread MRAB

sturlamolden wrote:

On Dec 12, 3:04 pm, Luis M. González  wrote:


Why don't you guys google a little bit to know what's being done to
address python's "slowness"??


Nothing is being done, and woth Py3k it got even worse.


It has been mentioned in this thread the pypy project (isn't it enough
for you??)
Other hints: shedskin, psyco, pyrex...


None of those projects addresses inefficacies in the CPython
interpreter, except for psyco - which died of an overdose PyPy.

PyPy is interesting if they ever will be able to produce something
useful. They have yet to prove that. Even if PyPy can come up with a
Python JIT, they will still be decades behind the technologies of
Strongtalk and Java. That is the problem with reinventing the wheel
all over again.

Not to forget LLVM and Parrot which also will support Python
frontends.

Python is developed and maintained by volunteers. If you'd like to have 
a go at writing a JIT interpreter for it, then go ahead. No-one here 
will stop you.

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


Re: Removing None objects from a sequence

2008-12-12 Thread pruebauno
On Dec 12, 8:08 am, "Filip Gruszczyński"  wrote:
> I am not doing it, because I need it. I can as well use "if not elem
> is None", but I just wanted to know, if there is some better way of
> doing this. I like to know :-)
>
> And I can't understand why you are becoming so aggressive because of
> this. Just because I asked for that, doesn't mean, that I will put
> some obfuscated code into my project. I just wanted to learn something
> new - I checked itertools, I googled a bit, now I wanted to ask here
> if someone knew some really cool way of this.  All the other
> assumptions weren't really necessary.
>
> Thanks for those ideas, however. I like the last one a lot :)
>
> --
> Filip Gruszczyński

In this case the "cool" way is the straightforward way:
either the list versions:

[x fox x in seq if x is not None]
filter(lambda x: x is not None, seq)

or the generator versions:

(x for x in seq if x is not None)
itertools.ifilter(lambda x: x is not None, seq)

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


Re: Python is slow

2008-12-12 Thread Stefan Behnel
sturlamolden wrote:
> How is the numpy support in Cython going? It was supposed to know
> about ndarrays natively.

It does.


> I.e. not treat them as Python objects, but
> rather as known C structs. That way an operation like arr[n] would not
> result in a callback to Python, but translate directly to fast pointer
> arithmetics.

http://docs.cython.org/docs/numpy_tutorial.html

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


Re: Interface & Implementation

2008-12-12 Thread rdmurray

On Fri, 12 Dec 2008 at 16:07, J Ramesh Kumar wrote:

I am new to python. I require some help on implementing interface and
its implementation. I could not find any sample code in the web. Can
you please send me some sample code which is similar to the below java
code ? Thanks in advance for your help.


public interface MyIfc
{
   public void myMeth1();
   public void myMeth2();
}

public class MyClass implements MyIfc
{
 public void myMeth1()
 {
 //do some implementation
 }

public void myMeth2()
  {
  //do some implementation
  }
}
...

MyClass myc=new MyClass();
Hashtable hash=new Hashtable();
hash.put("MYIFC",myc);

MyIfc myi=(MyIfc)hash.get("MYIFC");
myi.myMeth1();
myi.myMeth2();
.


The python 2.x way to to this would be:

class MyClass(object):

def myMeth1(self):
#do some implementation

def myMeth2(self):
#do some implementation

myc = MyClass()
hash = dict()
hash["MYIFC"] = myc
myi = hash["MYIFC"]
myi.myMeth1()
myi.myMeth2()

Which is to say, python 2.x does not have any formal notion
of interfaces.

In python 3.0 if you have a need for an interface you can do this:

from abc import ABCMeta, abstractmethod

class MyIfc:
__metaclass__ = ABCMeta

@abstractmethod
def myMeth1(self): pass

@abstractmethod
def myMeth2(self): pass


class MyClass(MyIfc):
[from here on just like above]

Note however, that an Abstract Base Class is _not_ the same thing
as a Java interface, though it can serve some of the same purposes.
See http://docs.python.org/dev/3.0/whatsnew/2.6.html#pep-3119 for
more.

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


Re: Removing None objects from a sequence

2008-12-12 Thread Vito De Tullio
Filip Gruszczyński wrote:

> I checked itertools, but the only thing that
> seemed ok, was ifilter - this requires seperate function though, so
> doesn't seem too short. 

is this too much long?

>>> from itertools import ifilter
>>> for element in ifilter(lambda x: x is not None, [0,1,2,None,3,None,4]):
... print element
...
0
1
2
3
4
>>>   

-- 
By ZeD

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


Re: newbie question: if var1 == var2:

2008-12-12 Thread J. Cliff Dyer

On Thu, 2008-12-11 at 13:44 -0600, Kirk Strauser wrote:
> At 2008-12-11T17:24:44Z, rdmur...@bitdance.com writes:
> 
> > >>> '  ab c  \r\n'.rstrip('\r\n')
> > '  ab c  '
> > >>> '  ab c  \n'.rstrip('\r\n')
> > '  ab c  '
> > >>> '  ab c  '.rstrip('\r\n')
> > '  ab c  '
> 
> I didn't say it couldn't be done.  I just like the Perl version better.

Python has a version equally good:

def chomp(s):
return s.rstrip('\r\n')

chomp("foo\n")
chomp("foo")
chomp("perl\r\n")

You'll hardly miss Perl at all. ;)

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


Re: concept of creating structures in python

2008-12-12 Thread Joe Strout

On Dec 11, 2008, at 10:52 PM, navneet khanna wrote:

I want to create a structure within a structure i.e. nested  
structures in python.

I tried with everything but its not working.
my code is like this:

class L(Structure):

def __init__(self,Name='ND',Addr=0,ds_obj = D()):


Change the default value of ds_obj here to None.  Otherwise, you will  
certainly confuse yourself (there would be just one default object  
shared among all instances).



self.Name = Name
self.Addr = Addr
self.ds_obj = ds_obj


class D(Structure):

def  __init__(self,dataName='ND',index = 0,ele_obj=E()):

self.dataName = dataName
self.index = index
self.ele_obj = ele_obj


Same thing here with ele_obj -- have it default to None to save  
yourself grief.


Otherwise, these look fine.


these are two structures. I want to refer D structure in L one and  
use it. I want to access the value of D structure like L.D.index = 0.


But you didn't name it "D" -- if you have an L object, say "foo", then  
you'd get to it's D object as foo.ds_obj (since that's what you named  
it in L.__init__).  If you then wanted to get to that thing's E  
object, it'd be foo.ds_obj.ele_obj.


Best,
- Joe

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


Re: Reading online zip files - zipfile and zlib, wbits

2008-12-12 Thread Brendan
On Dec 12, 10:46 am, Brendan  wrote:
> On Dec 12, 10:25 am, Brendan  wrote:
>
> > I am fooling around with accessing contents of zip files online. I
> > download the tail end of the zip and use zipfile to get the zip
> > central directory structure. I download the section of the zip file I
> > need, directly read the zip file headers and use that information with
> > zlib to uncompress the data. The files I am examining will always be
> > compressed using deflate, with a wbits value of -15(minus for
> > headerless data because I am unsure whether the zip file header is
> > what zlib expects).
>
> > I can not find anywhere in the PK Zip Application notes 
> > (http://www.pkware.com/documents/casestudies/APPNOTE.TXT) how to
> > determine the value I should uze for wbits with zlib.decompress. I
> > have determined it is -15 from experimentation. Does anyone know the
> > answer to this?
>
> Okay, I found part of the answer here in the zip app notes
> [quote]
> general purpose bit flag: (2 bytes)
>
>           Bit 0: If set, indicates that the file is encrypted.
>
>           (For Method 6 - Imploding)
>           Bit 1: If the compression method used was type 6,
>                  Imploding, then this bit, if set, indicates
>                  an 8K sliding dictionary was used.  If clear,
>                  then a 4K sliding dictionary was used.
>           Bit 2: If the compression method used was type 6,
>                  Imploding, then this bit, if set, indicates
>                  3 Shannon-Fano trees were used to encode the
>                  sliding dictionary output.  If clear, then 2
>                  Shannon-Fano trees were used.
>
>           (For Methods 8 and 9 - Deflating)
>           Bit 2  Bit 1
>             0      0    Normal (-en) compression option was used.
>             0      1    Maximum (-exx/-ex) compression option was
> used.
>             1      0    Fast (-ef) compression option was used.
>             1      1    Super Fast (-es) compression option was used.
> [/quote]
>
> Now I just don't understand Why Normal deflate corresponds to 15
> wbits, and why I have to use headerless for the data, i.e. wbits = -15.

Seems the bit flags are not properly set, bit 2 should be 0 and bit 1
should be 1, to correspond to maximum compression i.e. wbit = 15.
Still don't know why wbits has to be negative.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mathematica 7 compares to other languages

2008-12-12 Thread Tom McGlynn
On Dec 11, 6:46 am, "William James"  wrote:
> John W Kennedy wrote:
> > Xah Lee wrote:
> > > In lisp, python, perl, etc, you'll have 10 or so lines. In C or
> > > Java, you'll have 50 or hundreds lines.
>
> > Java:
>
> > static float[] normal(final float[] x) {
> >float sum = 0.0f;
> >for (int i = 0; i < x.length; ++i) sum += x[i] * x[i];
> >final float divisor = (float) Math.sqrt(sum);
> >float[] a = new float[x.length];
> >for (int i = 0; i < x.length; ++i) a[i] = x[i]/divisor;
> >return a;
> > }

Calculating the norm of a vector is a numeric operation, so not
surprising it's pretty
easy to do in Fortran.  While pre Fortran 90 would using something
similar to the above,
today you can do it as

norm = x/sqrt(sum(x*x))

for an arbitratry vector (or tensor for that matter).  It would take a
couple more lines to wrap it up in a function

real function norm(x)
real x(*)
norm = x/sqrt(sum(x*x))
end

[Caveat: my Fortran is more than rusty ]

So even Fortran can do this in only 1 line or 4 as a function.

Judging by the LOC and, at least to my eye, the clarity of the method,
Fortran is a real winner!  Just to give a tiny bit of Java relevance
to the discussion: It's the ability to write functions that
straightforwardly express the mathematical intent of the user that
makes operator overloading (in this case over arrays) so useful in
many numerical contexts.  This is cross-posted to Python as well.  I
understand it has similar array arithmetic capabilities to Fortran. I
believe this may be one reason for Python's burgeoning popularity

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


Re: Removing None objects from a sequence

2008-12-12 Thread Marco Mariani

Filip Gruszczyński wrote:



I am not doing it, because I need it. I can as well use "if not elem
is None",


I suggest "if elem is not None", which is not quite the same.

If you slip such an error in a post, I suggest to practice some time 
writing correct code before having one-liner contests with your 
perl-loving friends :)


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


Re: Python is slow

2008-12-12 Thread Christian Heimes
sturlamolden schrieb:
> On Dec 12, 3:04 pm, Luis M. González  wrote:
> 
>> Why don't you guys google a little bit to know what's being done to
>> address python's "slowness"??
> 
> Nothing is being done, and woth Py3k it got even worse.

Indeed, it *is* slower for now. As I already said in another thread our
top priorities were feature completeness and bug fixing. Optimizations
will follow the features in the near future.

Christian

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


Re: var or inout parm?

2008-12-12 Thread sturlamolden
On Dec 12, 3:54 pm, Steve Holden  wrote:
> sturlamolden wrote:
> > On Dec 12, 3:08 pm, Marc 'BlackJack' Rintsch  wrote:
>
> >> No bug because a mutation *is* attempted.  ``a += x`` calls `a.__iadd__`
> >> which *always* returns the result which is *always* rebound to the name
> >> `a`.  Even with mutable objects where `__iadd__()` simply returns
> >> `self`!
>
> > No, a mutation is not attempted, even if __iadd__() always returns a
> > value. If a rebinding of a member to the same member is attempted, the
> > tuple should not raise an exception. The tuple should check that it is
> > actually being *mutated* before it raises any exception. There is an
> > attempted write to the tuple, but not an attempted mutation of the
> > tuple. The tuple should tell the difference. Immutability does not
> > imply inwriteability, if the write operation changes nothing. But the
> > tuple raises an exception on any write attempt.
>
> OK, so if you regard the current behavior as a bug explain how to modify
> the tuple's __iadd__ method and the coding of the INPLACE_ADD operator.
> At least in pseudocode.
>
> Criticism is easy. Now demonstrate that it's *informed* criticism.
> Enough of the "should". I am always suspicious of suggestions that say
> what the interpreter "should" or "should not" do. It makes it sound as
> though you can wave a magic wand to achieve the desired behavior.


> The interpreter "should not" have a GIL.

> The tuple "should" check that
> it is actually being mutated. How?

In Python it would be something similar to:

def __setitem__(self, index, value):
   if _buf[index] is not value: # given that _buf is the tuple's
internal buffer
  raise TypeError, 'tuple' object does not support item
assignment

It should be the tuple's __setitem__ that was invoked here, not
__iadd__, or the parser is faulty.


S.M.



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


Re: var or inout parm?

2008-12-12 Thread sturlamolden
On Dec 12, 4:55 pm, sturlamolden  wrote:

> def __setitem__(self, index, value):
>if _buf[index] is not value: # given that _buf is the tuple's
> internal buffer
>   raise TypeError, 'tuple' object does not support item
> assignment

blæh, that should be self._buf[index]




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


Re: concept of creating structures in python

2008-12-12 Thread Steve Holden
Joe Strout wrote:
> On Dec 11, 2008, at 10:52 PM, navneet khanna wrote:
> 
>> I want to create a structure within a structure i.e. nested structures
>> in python.
>> I tried with everything but its not working.
>> my code is like this:
>>
>> class L(Structure):
>>
>> def __init__(self,Name='ND',Addr=0,ds_obj = D()):
> 
> Change the default value of ds_obj here to None.  Otherwise, you will
> certainly confuse yourself (there would be just one default object
> shared among all instances).
> 
>> self.Name = Name
>> self.Addr = Addr
>> self.ds_obj = ds_obj
>>
>>
>> class D(Structure):
>>
>> def  __init__(self,dataName='ND',index = 0,ele_obj=E()):
>>
>> self.dataName = dataName
>> self.index = index
>> self.ele_obj = ele_obj
> 
> Same thing here with ele_obj -- have it default to None to save yourself
> grief.
> 
> Otherwise, these look fine.
> 
Joe missed a piece out here. If you change the signature of your
D.__init__() to read

 def  __init__(self, dataName='ND', index = 0, ele_obj=None):

then you need to insert the following code at the top of the method:

if ele_obj is None:
ele_obj = E()

[You'll note, by the way, I have inserted standard spacing into the
"def" statement to enhance readbility: you should use spaces after all
commas if you want your code to be easy for other programmers to read).
This avoids a common beginner pitfall. Your original code would create a
single E object that would be used as the defauilt for all Ds created
without explicitly passing an ele_obj. Then if that object were changed
(mutated) in some way, all such E's would see a change had been made to
their ele_obj. With the extra code, a different ele_obj is created for
each E that isn't passed one.

The same argument applies to L.__init__()'s ds_obj argument.
> 
>> these are two structures. I want to refer D structure in L one and use
>> it. I want to access the value of D structure like L.D.index = 0.
> 
[...]

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: newbie question: if var1 == var2:

2008-12-12 Thread Kirk Strauser
At 2008-12-12T15:35:11Z, "J. Cliff Dyer"  writes:

> Python has a version equally good:
>
> def chomp(s):
> return s.rstrip('\r\n')
>
> You'll hardly miss Perl at all. ;)

I haven't missed Perl in years!  I just wish there was a basestring.stripeol
method because I seem to end up writing the inline version of "chomp" every
time I iterate across a file.
-- 
Kirk Strauser
The Day Companies
--
http://mail.python.org/mailman/listinfo/python-list


Re: concept of creating structures in python

2008-12-12 Thread Joe Strout

On Dec 12, 2008, at 9:00 AM, Steve Holden wrote:


Change the default value of ds_obj here to None.  Otherwise, you will
certainly confuse yourself (there would be just one default object
shared among all instances).


Joe missed a piece out here. If you change the signature of your
D.__init__() to read

def  __init__(self, dataName='ND', index = 0, ele_obj=None):

then you need to insert the following code at the top of the method:

   if ele_obj is None:
   ele_obj = E()


Yes, if you really need to guarantee that ele_obj is not None, then  
this is the way to do it.


Of course this would mean that you can't get a None ele_obj even by  
passing it in explicitly as the parameter value -- if you need to  
support that as well, then the solution is a little more complex.   
Perhaps best in that case would be to just not give ele_obj any  
default value at all, so it becomes a required parameter.


Best,
- Joe

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


Re: var or inout parm?

2008-12-12 Thread Steve Holden
sturlamolden wrote:
> On Dec 12, 3:54 pm, Steve Holden  wrote:
[...]
>> The interpreter "should not" have a GIL.
> 
>> The tuple "should" check that
>> it is actually being mutated. How?
> 
> In Python it would be something similar to:
> 
> def __setitem__(self, index, value):
>if _buf[index] is not value: # given that _buf is the tuple's
> internal buffer
>   raise TypeError, 'tuple' object does not support item
> assignment
> 
> It should be the tuple's __setitem__ that was invoked here, not
> __iadd__, or the parser is faulty.
> 
OK, so now you are proposing to alter the parser, and possibly the
implementation of the INPLACE_ADD opcode in eval.c, so can you give us
the patch for those, please?

This is exactly the point I was trying to make. It's easy to stand on
the sidelines and make sensible- or even intelligent-sounding
suggestions about how to change Python. But inside the interpreter
there's a maze of twisty little passages all alike (or similar
complexity), and hand-waving doesn't get you anywhere.

Discussion of such behavior as a "bug" is also pejorative, since the
current semantics are the way they are by design. You are therefore
disagreeing with the design of Python rather than discussing a bug in
its implementation.

That also raises the issues of how you get Jython and IronPython to
implement the same semantics, and whether you care about the millions of
lines of code that already assumes the current behavior.

You've got a lot of work to do ...

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Removing None objects from a sequence

2008-12-12 Thread Marc 'BlackJack' Rintsch
On Fri, 12 Dec 2008 16:51:15 +0100, Marco Mariani wrote:

> Filip Gruszczyński wrote:
> 
> 
>> I am not doing it, because I need it. I can as well use "if not elem is
>> None",
> 
> I suggest "if elem is not None", which is not quite the same.

In which way is it not the same?  Has the same behavior at least:

In [256]: elem = None

In [257]: not elem is None
Out[257]: False

In [258]: elem is not None
Out[258]: False

In [259]: elem = 42

In [260]: not elem is None
Out[260]: True

In [261]: elem is not None
Out[261]: True

> If you slip such an error in a post, I suggest to practice some time
> writing correct code before having one-liner contests with your
> perl-loving friends :)

If you call something an error, make sure it really is one.  :-)

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Removing None objects from a sequence

2008-12-12 Thread Kirk Strauser
At 2008-12-12T15:51:15Z, Marco Mariani  writes:

> Filip Gruszczyński wrote:
>
>> I am not doing it, because I need it. I can as well use "if not elem
>> is None",

> I suggest "if elem is not None", which is not quite the same.

So what's the difference exactly?  "foo is not None" is actually surprising
to me, since "not None" is True.  "0 is True" is False, but "0 is not None"
is True.  Why is that?
-- 
Kirk Strauser
The Day Companies
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reading online zip files - zipfile and zlib, wbits

2008-12-12 Thread Brendan
On Dec 12, 11:36 am, Brendan  wrote:
> On Dec 12, 10:46 am, Brendan  wrote:
>
>
>
>
>
> > On Dec 12, 10:25 am, Brendan  wrote:
>
> > > I am fooling around with accessing contents of zip files online. I
> > > download the tail end of the zip and use zipfile to get the zip
> > > central directory structure. I download the section of the zip file I
> > > need, directly read the zip file headers and use that information with
> > > zlib to uncompress the data. The files I am examining will always be
> > > compressed using deflate, with a wbits value of -15(minus for
> > > headerless data because I am unsure whether the zip file header is
> > > what zlib expects).
>
> > > I can not find anywhere in the PK Zip Application notes 
> > > (http://www.pkware.com/documents/casestudies/APPNOTE.TXT) how to
> > > determine the value I should uze for wbits with zlib.decompress. I
> > > have determined it is -15 from experimentation. Does anyone know the
> > > answer to this?
>
> > Okay, I found part of the answer here in the zip app notes
> > [quote]
> > general purpose bit flag: (2 bytes)
>
> >           Bit 0: If set, indicates that the file is encrypted.
>
> >           (For Method 6 - Imploding)
> >           Bit 1: If the compression method used was type 6,
> >                  Imploding, then this bit, if set, indicates
> >                  an 8K sliding dictionary was used.  If clear,
> >                  then a 4K sliding dictionary was used.
> >           Bit 2: If the compression method used was type 6,
> >                  Imploding, then this bit, if set, indicates
> >                  3 Shannon-Fano trees were used to encode the
> >                  sliding dictionary output.  If clear, then 2
> >                  Shannon-Fano trees were used.
>
> >           (For Methods 8 and 9 - Deflating)
> >           Bit 2  Bit 1
> >             0      0    Normal (-en) compression option was used.
> >             0      1    Maximum (-exx/-ex) compression option was
> > used.
> >             1      0    Fast (-ef) compression option was used.
> >             1      1    Super Fast (-es) compression option was used.
> > [/quote]
>
> > Now I just don't understand Why Normal deflate corresponds to 15
> > wbits, and why I have to use headerless for the data, i.e. wbits = -15.
>
> Seems the bit flags are not properly set, bit 2 should be 0 and bit 1
> should be 1, to correspond to maximum compression i.e. wbit = 15.
> Still don't know why wbits has to be negative.- Hide quoted text -
>
> - Show quoted text -

Arg!  Tried a different tack. Took the file header plus compressed
file and concatenated with central directory. Now need only zipfile
module.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Removing None objects from a sequence

2008-12-12 Thread Marco Mariani

Kirk Strauser wrote:


So what's the difference exactly?  "foo is not None" is actually surprising
to me, since "not None" is True.  "0 is True" is False, but "0 is not None"
is True.  Why is that?


Cause I was tired of course, and got the not precedente not right!! Argh
--
http://mail.python.org/mailman/listinfo/python-list


Re: var or inout parm?

2008-12-12 Thread Marc 'BlackJack' Rintsch
On Fri, 12 Dec 2008 07:56:58 -0800, sturlamolden wrote:

> On Dec 12, 4:55 pm, sturlamolden  wrote:
> 
>> def __setitem__(self, index, value):
>>if _buf[index] is not value: # given that _buf is the tuple's
>> internal buffer
>>   raise TypeError, 'tuple' object does not support item
>> assignment
> 
> blæh, that should be self._buf[index]

But then the error message is not true anymore because tuples *would* 
support item assignment when the old and new value are the same.  Which 
leads to strange things like code that may or may not raise that 
exception, depending on implementation details:

t = (1, 2)
t[0] = 1   # Maybe okay -- maybe not.
t[1] += 0  # Same here.

I'd find that quite odd.

Ciao,
Marc 'BlackJack' Rintsch

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


Re: How do I manually uninstall setuptools (installed by egg)?

2008-12-12 Thread Nick Craig-Wood
David Cournapeau  wrote:
>  On Thu, Dec 11, 2008 at 10:30 PM, Nick Craig-Wood  
> wrote:
> > David Cournapeau  wrote:
> >>  On Wed, Dec 10, 2008 at 12:04 PM, Chris Rebert  wrote:
> >> > On Tue, Dec 9, 2008 at 6:49 PM,   wrote:
> >> >> On Ubuntu, I accidentally manually installed setuptools
> >> >> http://pypi.python.org/pypi/setuptools/0.6c9 (by running the .egg file
> >> >> as a shell script via sudo), and now realize I should just be using
> >> >> apt to take care of my system Python packages.
> >> >
> >> > Really, why? setuptools has more Python packages/programs available
> >> > and updates faster than Debian.
> >> > It's also likely that some of the Debian Python packages are installed
> >> > using setuptools anyway.
> >> > So, why do you think apt and not setuptools is The Right Way(tm)?
> >>
> >>  Setuptools is certainly not the right way to install packages
> >>  system-wide on debian, it is very likely to break the whole thing.
> >
> > It wouldn't be too difficult to make a .deb target which would collect
> > all the files that did get installed into a package.  It would be a
> > rather rough and ready package but would do the job.
> 
>  Depends what you mean by would do the job: rather rough certainly does
>  not mean "would do the job" for something as essential as a package
>  IMO.

Essentially a package has files in it in a fixed possition in the
filesystem.  The package manager's (dpkg at this level) job is to keep
track of those file and tell you about conflicts.

You can use alien to turn a tar.gz into a perfectly usable debian
package.  It won't have dependencies, or help or any of the other
things a package needs to be a proper package, but it satisfies my
basic needs that all software is installed as packages, so it can be
uninstalled cleanly.

> > The .deb would then be uninstallable in the usual (dpkg --purge) way.
> >
> > Did anyone think about that?
> 
>  Yes, there is stddeb which does that (make a .deb package from a
>  setuptools package).

Cool, I've not seen that before.  Probably because it isn't in debian!

> > easy_install can do that I think...
> 
>  Not without a lot of hoola, unfortunately; for example, it breaks
>  stow, so I have to use specialy scripts to circumvent the damn thing
>  and make it what I tell him to do. I never understood what's easy
>  about easy install: it is broken in so many ways, and has caused me so
>  many pains - even when I was not using - that I do not trust it at
>  all. I only use it to download packages (and even then it manage to
>  fail more than work), and always install them from setup.py afterwards
>  (at which step I of course also have to circumvent setuptools if the
>  package uses setuptools).

;-)

As a mostly linux developer I always install stuff in packages if
possible.

Failing that I'll use bdist_rpm then alien to convert to a deb which
works well enough I find.

However when I have to make my stuff work on Windows, I find
easy_install to be a fantastic timesaver as compared to looking for
the package on a web site, downloading it, unpacking it installing it
and then repeating for all the dependencies.

easy_install is a long way from being a proper package manager though
:-(

I guess it is aiming at the same territory as the cpan installer with
perl.  My experiences with that is that it works very well, but again
splatters untracked files all over your filesystem.  Debian comes with
dh-make-perl which can use CPAN directly to make .debs which works
quite well.  Something similar based on easy_install for python would
be ideal.  It looks like stdeb could become that one day.

-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: var or inout parm?

2008-12-12 Thread sturlamolden
On Dec 12, 5:13 pm, Steve Holden  wrote:

> > It should be the tuple's __setitem__ that was invoked here, not
> > __iadd__, or the parser is faulty.
>
> OK, so now you are proposing to alter the parser, and possibly the
> implementation of the INPLACE_ADD opcode in eval.c, so can you give us
> the patch for those, please?

What? Take a look at the code again:

mytuple[0] += 1

should never attempt an __iadd__ on mytuple.

A sane parser would see this as:

tmp = mytuple.__getitem__(0)
tmp = tmp.__iadd__(1)
mytuple.__setitem__(0, tmp) # should this always raise an exception?


> Discussion of such behavior as a "bug" is also pejorative, since the
> current semantics are the way they are by design.

Right, this bug is by design. You learned that phrase from a guy in
Redmond?



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


Re: Removing None objects from a sequence

2008-12-12 Thread MRAB

Kirk Strauser wrote:

At 2008-12-12T15:51:15Z, Marco Mariani  writes:


Filip Gruszczyński wrote:


I am not doing it, because I need it. I can as well use "if not elem
is None",



I suggest "if elem is not None", which is not quite the same.


So what's the difference exactly?  "foo is not None" is actually surprising
to me, since "not None" is True.  "0 is True" is False, but "0 is not None"
is True.  Why is that?

>
I suppose that it should really be "not is" (cp "not in"), but Guido 
chose to follow the English pattern "is not". "not" returns a Boolean 
(or originally an int) and "is" checks for identity, but the result of 
"is False" or "is True" is down to implementation details in the 
interpreter, so you wouldn't write "is not ..." to mean "is (not ...)" 
anyway, and in practice it's not a problem.

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


Re: newbie question: if var1 == var2:

2008-12-12 Thread MRAB

Kirk Strauser wrote:

At 2008-12-12T15:35:11Z, "J. Cliff Dyer"  writes:


Python has a version equally good:

def chomp(s):
return s.rstrip('\r\n')

You'll hardly miss Perl at all. ;)


I haven't missed Perl in years!  I just wish there was a basestring.stripeol
method because I seem to end up writing the inline version of "chomp" every
time I iterate across a file.

>
Python is open source. You could suggest adding it and/or provide a patch.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Removing None objects from a sequence

2008-12-12 Thread Steve Holden
Kirk Strauser wrote:
> At 2008-12-12T15:51:15Z, Marco Mariani  writes:
> 
>> Filip Gruszczyński wrote:
>>
>>> I am not doing it, because I need it. I can as well use "if not elem
>>> is None",
> 
>> I suggest "if elem is not None", which is not quite the same.
> 
> So what's the difference exactly?  "foo is not None" is actually surprising
> to me, since "not None" is True.  "0 is True" is False, but "0 is not None"
> is True.  Why is that?

"is not" is an operator, so the parse is

foo (is not) None

not

foo is (not None)

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: var or inout parm?

2008-12-12 Thread Steve Holden
sturlamolden wrote:
> On Dec 12, 5:13 pm, Steve Holden  wrote:
> 
>>> It should be the tuple's __setitem__ that was invoked here, not
>>> __iadd__, or the parser is faulty.
>> OK, so now you are proposing to alter the parser, and possibly the
>> implementation of the INPLACE_ADD opcode in eval.c, so can you give us
>> the patch for those, please?
> 
> What? Take a look at the code again:
> 
> mytuple[0] += 1
> 
> should never attempt an __iadd__ on mytuple.
> 
> A sane parser would see this as:
> 
> tmp = mytuple.__getitem__(0)
> tmp = tmp.__iadd__(1)
> mytuple.__setitem__(0, tmp) # should this always raise an exception?
> 
> 
>> Discussion of such behavior as a "bug" is also pejorative, since the
>> current semantics are the way they are by design.
> 
> Right, this bug is by design. You learned that phrase from a guy in
> Redmond?
> 
"It's not a bug, it's a feature" predates Microsoft by several years.

If I say you are ugly, that doesn't make it true. Neither does your
calling this a bug make it a bug.

The fact is that Python doesn't behave the way you want it to. If your
friend doesn't want to do what you do, does that make it a bug in his
behavior. You're being a little juvenile here.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: var or inout parm?

2008-12-12 Thread sturlamolden
On Dec 12, 5:13 pm, Steve Holden  wrote:

> OK, so now you are proposing to alter the parser, and possibly the
> implementation of the INPLACE_ADD opcode in eval.c, so can you give us
> the patch for those, please?

That is not where the problem resides.

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


Re: concept of creating structures in python

2008-12-12 Thread Steve Holden
Joe Strout wrote:
> On Dec 12, 2008, at 9:00 AM, Steve Holden wrote:
> 
>>> Change the default value of ds_obj here to None.  Otherwise, you will
>>> certainly confuse yourself (there would be just one default object
>>> shared among all instances).
>>>
>> Joe missed a piece out here. If you change the signature of your
>> D.__init__() to read
>>
>> def  __init__(self, dataName='ND', index = 0, ele_obj=None):
>>
>> then you need to insert the following code at the top of the method:
>>
>>if ele_obj is None:
>>ele_obj = E()
> 
> Yes, if you really need to guarantee that ele_obj is not None, then this
> is the way to do it.
> 
> Of course this would mean that you can't get a None ele_obj even by
> passing it in explicitly as the parameter value -- if you need to
> support that as well, then the solution is a little more complex. 
> Perhaps best in that case would be to just not give ele_obj any default
> value at all, so it becomes a required parameter.
> 
Just for completeness, if you want to be able to pass None then you need
to create a sentinel object, usually just an instantiation of object(),
and test for identity with that to determine that no argument was provided.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Python extension: callbacks blocked when holding button down

2008-12-12 Thread alan . chambers
I'm developing a Python extension. It's a wrapper for some firmware,
and simulates the target hardware environment. I'm using wxPython. I
pass a function to the extension so it can let Python know about
certain events.
The code is currently single threaded.

My problem is that the callback seems to have no effect if it is
called while I am holding down a wxButton in the Python GUI. Long
button presses are significant in the firmware so this seems a bit
limiting.

Can anyone explain what is going on? What's the best workaround?

Thanks.


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


Re: Mathematica 7 compares to other languages

2008-12-12 Thread George Neuner
On Wed, 10 Dec 2008 21:37:34 + (UTC), Kaz Kylheku
 wrote:

>Now try writing a device driver for your wireless LAN adapter in Mathematica.

Notice how Xah chose not to respond to this.

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


Re: Bidirectional Networking

2008-12-12 Thread Emanuele D'Arrigo
Thank you both for the suggestions! Eventually I tried with threading
as illustrated in the code below.
And it works pretty well! The only problem I'm having with it is that
as the server is a daemon the program should end when the client
thread cease to be alive. But it doesn't seem to work that way and I'm
not sure what's going on! I did achieve my objective though. Two
separate instances of the code below will happily send random numbers
to each other for a few seconds!

Manu

-
To use the following code, cut&paste into two separate *.py files and
invert the port numbers in one file. Then, start them in two separate
shells. WARNING: as mentioned above the two program do not exit and
must be killed, i.e. through the Windows Task Manager or the unix kill
command.
-

import SocketServer
import socket
import threading
import random
from time import sleep

## Network request handler
class MyTCPHandler(SocketServer.StreamRequestHandler):

def handle(self):
self.data = self.rfile.readline().strip()
print "-> RECV: " + self.data + " - Sent by:" +
self.client_address[0]

## Server Thread
class AsyncServer(threading.Thread):
def __init__(self, localServer):
threading.Thread.__init__(self)
self.server = SocketServer.TCPServer(localServer,
MyTCPHandler)
def run(self):
self.server.serve_forever()

## Client Thread
class AsyncClient(threading.Thread):

def __init__(self, remoteServer):
threading.Thread.__init__(self)
self.remoteServer = remoteServer

def run(self):
cycle = 0
while cycle < 1000:

chance = random.random()
if(chance < 0.01):

randomNumber = int(random.random() * 1000)
message = str(randomNumber) + " from remote cycle " +
str(cycle)

try:
sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
sock.connect(self.remoteServer)
sock.send(message + "\n")
sock.close()
print("SENT ->: "+str(randomNumber)+ " by local
cycle "+str(cycle))
except:
print("Failed to send number on cycle "+str
(cycle))
pass

cycle += 1

sleep(0.01)

## Simulating local/remote servers with different ports
localServer = ("localhost", )
remoteServer = ("localhost", 1)

asyncServer = AsyncServer(localServer)
asyncServer.daemon = True
asyncServer.start()

asyncClient = AsyncClient(remoteServer)
asyncClient.start()

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


Re: Python is slow

2008-12-12 Thread Luis M . González
On Dec 12, 11:17 am, sturlamolden  wrote:
> On Dec 12, 3:04 pm, Luis M. González  wrote:
>
> > Why don't you guys google a little bit to know what's being done to
> > address python's "slowness"??
>
> Nothing is being done, and woth Py3k it got even worse.
>
> > It has been mentioned in this thread the pypy project (isn't it enough
> > for you??)
> > Other hints: shedskin, psyco, pyrex...
>
> None of those projects addresses inefficacies in the CPython
> interpreter, except for psyco - which died of an overdose PyPy.
>
> PyPy is interesting if they ever will be able to produce something
> useful. They have yet to prove that. Even if PyPy can come up with a
> Python JIT, they will still be decades behind the technologies of
> Strongtalk and Java. That is the problem with reinventing the wheel
> all over again.
>
> Not to forget LLVM and Parrot which also will support Python
> frontends.

So, what's your conclusion?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mathematica 7 compares to other languages

2008-12-12 Thread George Neuner
On Thu, 11 Dec 2008 10:41:59 -0800 (PST), Xah Lee 
wrote:

>On Dec 10, 2:47 pm, John W Kennedy  wrote:
>> Xah Lee wrote:
>> > In lisp, python, perl, etc, you'll have 10 or so lines. In C or Java,
>> > you'll have 50 or hundreds lines.
>>
>> C:
>>
>> #include 
>> #include 
>>
>> void normal(int dim, float* x, float* a) {
>>     float sum = 0.0f;
>>     int i;
>>     float divisor;
>>     for (i = 0; i < dim; ++i) sum += x[i] * x[i];
>>     divisor = sqrt(sum);
>>     for (i = 0; i < dim; ++i) a[i] = x[i]/divisor;
>>
>> }
>
>i don't have experience coding C. 

Then why do you talk about it as if you know something?

>The code above doesn't seems to satisfy the spec.

It does.

>The input should be just a vector, array, list, or
>whatever the lang supports. The output is the same 
>datatype of the same dimension.

C's native arrays are stored contiguously.  Multidimensional arrays
can be accessed as a vector of length (dim1 * dim2 * ... * dimN).

This code handles arrays of any dimensionality.  The poorly named
argument 'dim' specifies the total number of elements in the array.

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


Re: Python is slow

2008-12-12 Thread Andreas Kostyrka
On Fri, Dec 12, 2008 at 06:17:43AM -0800, sturlamolden wrote:
> None of those projects addresses inefficacies in the CPython
> interpreter, except for psyco - which died of an overdose PyPy.

Bullshit. All that discussion about performance forgets that performance is a 
function of the whole system, not the language.

Worse you can measure it really badly.

E.g. it's relative simple to compare CPython versus IronPython versus Jython. 
For a given benchmark program.

As programs do not trivially translate from language A to language B, nor does 
fluency in language A make you automatically fluent in
language B after learning the syntax.



> 
> PyPy is interesting if they ever will be able to produce something
> useful. They have yet to prove that. Even if PyPy can come up with a
> Python JIT, they will still be decades behind the technologies of
> Strongtalk and Java. That is the problem with reinventing the wheel
> all over again.

Well, it's reinventing the wheel. The problem that Java is a different kind of 
wheel 
(boxed vs. unboxed objects, plus more static compile time bindings), Smalltalk 
is also different (e.g. multiple inheritence),
so you need to have a specific toolbox for the wheel, sorry. Keeping and 
enhancing the tribal wisdom
about toolbox design is what a subtribe of the Computer Scientists do.

Btw, Psyco is not a JIT like most JVMs had them, it's a specializing compiler. 
JVM JITs traditionally speeded up the unboxed data 
type operations. Psyco does something comparable, but it has to specialize 
first on data types. The end effect is similiar, but the 
background of what happens is quite different.

> 
> Not to forget LLVM and Parrot which also will support Python
> frontends.
When they do, they'll do. There have flown quite a bit of Python version since 
the time that it was announced that
Parrot will have a Python frontend.

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


newbie question...

2008-12-12 Thread trfilmographer
Hi!

Im new at python and I just want to know if (and how) it is possible
to send parameters to a program.

what I mean is that when we start python I can call a file that should
be run like this: python myfile.py
can I send additional parameters along with it?  like::: python
myfile.py myVar1 myVar2

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


Re: newbie question...

2008-12-12 Thread Tim Chase

Im new at python and I just want to know if (and how) it is possible
to send parameters to a program.

what I mean is that when we start python I can call a file that should
be run like this: python myfile.py
can I send additional parameters along with it?  like::: python
myfile.py myVar1 myVar2


You're looking for sys.argv:

 t...@rubbish:~$ python - one two
 Python 2.5.2 (r252:60911, May 28 2008, 08:35:32)
[GCC 4.2.4 (Debian 4.2.4-1)] on linux2
Type "help", "copyright", "credits" or "license" for more 
information.

 >>> import sys
 >>> sys.argv
 ['-', 'one', 'two']


-tkc



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


Re: newbie question...

2008-12-12 Thread r
yes, but your script will need to know hoe to handle this.the
following will open a file who's name was passed to the script

if len(sys.argv) > 1:
try:
open_file(fname=sys.argv[1])
except:
pass
--
http://mail.python.org/mailman/listinfo/python-list


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Benjamin Kaplan
On Fri, Dec 12, 2008 at 12:50 PM, Dennis Lee Bieber
wrote:

> On Fri, 12 Dec 2008 03:42:55 -0800 (PST), feb...@gmail.com declaimed the
> following in comp.lang.python:
>
> > #!/usr/bin/python
> > #Py3k, UTF-8
> >
> > bank = int(input("How much money is in your account?\n>>"))
> > target = int(input("How much money would you like to earn each year?
> > \n>>"))
> >
>Just for my curiosity -- did Python 3.x (besides turning print into
> a function) also change input() to behave as the old raw_input()?
>

Yes.


>
>The above would be very discouraged in Python 2.x... in favor of ...
> int(raw_input(...))


>
>
> --
>WulfraedDennis Lee Bieber   KD6MOG
>wlfr...@ix.netcom.com   wulfr...@bestiaria.com
>HTTP://wlfraed.home.netcom.com/
>(Bestiaria Support Staff:   web-a...@bestiaria.com)
>HTTP://www.bestiaria.com/
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Tim Rowe
Since we all seem to be having a go, here's my take. By pulling the
rates and thresholds into a dictionary I feel I'm getting a step
closer to the real world, where these would presumably be pulled in
from a database and the number of interest bands might vary. But is
there a tidier way to get 'thresholds'? I was a bit surprised that
rates.keys() didn't give me a list directly, so although the 3.0
tutorial says "The keys() method of a dictionary object returns a list
of all the keys used in the dictionary, in arbitrary order (if you
want it sorted, just apply the sort() method to )" that's not /quite/
such a given, because "the list of keys" doesn't seem to be there for
the sorting any more.

Is there a tidy way of making rates and thresholds local to get_rate,
without recalculating each time? I suppose going object oriented is
the proper way.

#Py3k,UTF-8

rates = {0: 0.006, 1: 0.0085, 25000: 0.0124, 5: 0.0149, 10: 0.0173}
thresholds = list(rates.keys())
thresholds.sort()
thresholds.reverse()

def get_rate(balance):
for threshold in thresholds:
if balance >= threshold:
return rates[threshold]
else:
return 0.0

balance = int(input("How much money is in your account?\n>>"))
target = int(input("How much money would you like to earn each year?\n>>"))

if balance <= 0:
print("You'll never make your fortune that way!\n")
else:
interest = 0
year = 0
while interest < target:
rate = get_rate(balance)
interest = balance * rate
balance += interest
year += 1
print("Year %s, at %s rate: %s paid, %s in bank." % (year,
rate, interest, balance))


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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread MRAB

Tim Rowe wrote:

Since we all seem to be having a go, here's my take. By pulling the
rates and thresholds into a dictionary I feel I'm getting a step
closer to the real world, where these would presumably be pulled in
from a database and the number of interest bands might vary. But is
there a tidier way to get 'thresholds'? I was a bit surprised that
rates.keys() didn't give me a list directly, so although the 3.0
tutorial says "The keys() method of a dictionary object returns a list
of all the keys used in the dictionary, in arbitrary order (if you
want it sorted, just apply the sort() method to )" that's not /quite/
such a given, because "the list of keys" doesn't seem to be there for
the sorting any more.

Is there a tidy way of making rates and thresholds local to get_rate,
without recalculating each time? I suppose going object oriented is
the proper way.

#Py3k,UTF-8

rates = {0: 0.006, 1: 0.0085, 25000: 0.0124, 5: 0.0149, 10: 0.0173}
thresholds = list(rates.keys())
thresholds.sort()
thresholds.reverse()

Why are you putting them into a dict at all? Surely a list of tuples is 
better?


# I could've just written the list in descending order here!
rates = [(0, 0.006), (1, 0.0085), (25000, 0.0124), (5, 0.0149), 
(10, 0.0173)]

thresholds.sort(reversed=True)


def get_rate(balance):
for threshold in thresholds:
if balance >= threshold:
return rates[threshold]
else:
return 0.0



def get_rate(balance):
for threshold, rate in thresholds:
if balance >= threshold:
return rate
return 0.0


balance = int(input("How much money is in your account?\n>>"))
target = int(input("How much money would you like to earn each year?\n>>"))

if balance <= 0:
print("You'll never make your fortune that way!\n")
else:
interest = 0
year = 0
while interest < target:
rate = get_rate(balance)
interest = balance * rate
balance += interest
year += 1
print("Year %s, at %s rate: %s paid, %s in bank." % (year,
rate, interest, balance))


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


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread Kirk Strauser
At 2008-12-12T18:12:39Z, "Tim Rowe"  writes:

> Is there a tidy way of making rates and thresholds local to get_rate,
> without recalculating each time? I suppose going object oriented is
> the proper way.
>
> #Py3k,UTF-8
>
> rates = {0: 0.006, 1: 0.0085, 25000: 0.0124, 5: 0.0149, 10: 
> 0.0173}
> thresholds = list(rates.keys())
> thresholds.sort()
> thresholds.reverse()
>
> def get_rate(balance):
> for threshold in thresholds:
> if balance >= threshold:
> return rates[threshold]
> else:
> return 0.0

How 'bout:

def get_rate(balance):
for threshold, rate in ((10, .0173),
(5, .0149),
(25000, .0124),
(1, .0085),
(0, .006)):
if balance > threshold:
return rate
return .0
-- 
Kirk Strauser
The Day Companies
--
http://mail.python.org/mailman/listinfo/python-list


Re: (Very Newbie) Problems defining a variable

2008-12-12 Thread John Machin
On Dec 13, 4:50 am, Dennis Lee Bieber  wrote:
> On Fri, 12 Dec 2008 03:42:55 -0800 (PST), feb...@gmail.com declaimed the
> following in comp.lang.python:
>
> > #!/usr/bin/python
> > #Py3k, UTF-8
>
> > bank = int(input("How much money is in your account?\n>>"))
> > target = int(input("How much money would you like to earn each year?
> > \n>>"))
>
>         Just for my curiosity -- did Python 3.x (besides turning print into
> a function) also change input() to behave as the old raw_input()?

Yup. There've been some other tectonic plate shift effects, e.g.:

xrange() -> range(); range() -> list(range())
dict.iteritems() -> dict.items(); dict.items() -> list(dict.items())
halfassci() -> repr(); repr() -> ascii()

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


Re: newbie question...

2008-12-12 Thread trfilmographer
On Dec 12, 12:59 pm, r  wrote:
> yes, but your script will need to know hoe to handle this.the
> following will open a file who's name was passed to the script
>
> if len(sys.argv) > 1:
>     try:
>         open_file(fname=sys.argv[1])
>     except:
>         pass



ah, ok.  now what if I want the variable to be an integer that I
send?  for instance if I send 99 to the program, it is picking it up
as a string instead of an integer value.  How do I handle this with
python??
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python extension: callbacks blocked when holding button down

2008-12-12 Thread skip

alan> I'm developing a Python extension. It's a wrapper for some
alan> firmware, and simulates the target hardware environment. I'm using
alan> wxPython. I pass a function to the extension so it can let Python
alan> know about certain events.  The code is currently single threaded.

alan> My problem is that the callback seems to have no effect if it is
alan> called while I am holding down a wxButton in the Python GUI. Long
alan> button presses are significant in the firmware so this seems a bit
alan> limiting.

alan> Can anyone explain what is going on? What's the best workaround?

You don't say what platform you're running on, but in many environments,
holding down a menu button "grabs" the window server for the duration of the
button press.  This is certainly the case on Unix running the X Window
System.  In many cases multithreading is the best way around this problem.

-- 
Skip Montanaro - s...@pobox.com - http://smontanaro.dyndns.org/
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >