Re: Bored.

2009-11-30 Thread Bram Mertens

Ben Finney wrote:

geremy condra  writes:


On Mon, Nov 30, 2009 at 5:14 PM, Necronymouse  wrote:

Hello, I am learning python for about 2 years and I am bored. Not
with python but I have a little problem, when i want to write
something I realise that somebody had alredy written it!


That's great news: it means you can learn by example, and also learn the
more important skills of collaborating with other developers.


I'd find a big project and contribute to it. There's a lot more to
being a developer than writing code, and its hard to learn much about
that side of things by working on your own projects all the time.
Plus, it can be very satisfying to make a widely used piece of
software better.


This is good advice.

I would also say that it can be very satisfying contributing on a
*small* project: there is usually less communication overhead since
there are fewer people that need to communicate (the principles explored
in “The Mythical Man-Month”). On a small project, too, you can often
have a bigger impact which for many people is more satisfying.

So, in general: when you realise someone has already written something
you want to use, then start using it! You will quickly find that it
doesn't quite do everything you want, so that's your opportunity to make
improvements and start working with the existing developers.



How about http://sourceforge.net/search/?type_of_search=soft&words=python ?

Pick a project you like I'd be surprised if you'd be turned down when 
offering help to any of these.

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


Re: peppy

2009-11-30 Thread Nobody
On Tue, 01 Dec 2009 08:51:20 +0200, Johann Spies wrote:

> After reading about peppy on Freshmeat I decided to try it out after
> installing it using easy_install.  But:
> 
> $ peppy

>   File 
> "/usr/lib/python2.5/site-packages/peppy-0.13.2-py2.5.egg/peppy/lib/multikey.py",
>  line 120, in 
> 'C-': wx.ACCEL_CMD,
> AttributeError: 'module' object has no attribute 'ACCEL_CMD'

wx.ACCEL_CMD exists in wxPython 2.8 but not in 2.6, so I'd guess that
peppy requires 2.8 but you have 2.6 (or if you have both, 2.6 is the
default).

> This is on Debian squeeze.
> 
> How do I solve this?

First, ensure that wxPython 2.8 is installed. If you have both 2.6 and
2.8, you may need to add the following at the beginning of the main
"peppy" script:

import wxversion
wxversion.select("2.8")

This will cause subsequent "import wx" commands to use wxPython 2.8.

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


Re: a 100-line indentation-based preprocessor for HTML

2009-11-30 Thread Steve Howell
On Nov 28, 4:46 am, "Colin W."  wrote:
> On 27-Nov-09 22:04 PM, Steve Howell wrote:
>
>
>
> > Python has this really neat idea called indentation-based syntax, and
> > there are folks that have caught on to this idea in the HTML
> > community.
>
> > AFAIK the most popular indentation-based solution for generating HTML
> > is a tool called HAML, which actually is written in Ruby.
>
> > I have been poking around with the HAML concepts in Python, with the
> > specific goal of integrating with Django.   But before releasing that,
> > I thought it would be useful to post code that distills the basic
> > concept with no assumptions about your target renderer.  I hope it
> > also serves as a good example of what you can do in exactly 100 lines
> > of Python code.
>
> > Here is what it does...
>
> >      You can use indentation syntax for HTML tags like table.
>
> >      From this...
>
> >      table
> >          tr
> >              td
> >                  Left
> >              td
> >                  Center
> >              td
> >                  Right
>
> >      ...you get this:
> >  ...
>
> [snip]
>
> This is a neat idea but would a two character indentation not be enough?
>

The code actually preserves whatever indent style you give as input,
as long as you are consistent.  I used 4-space indents in my examples
since that seems to be the convention in Python, but when I did my
stint in Ruby, I got pretty comfortable with 2-space indents as well,
and I think it can make sense for HTML, where you do get pretty deep
sometimes with idioms like table/tr/td.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python and vc numbers

2009-11-30 Thread Nobody
On Mon, 30 Nov 2009 21:02:00 +1100, Daniel Dalton wrote:

>> That did the trick, thanks, after I append 
>> [-2] 
> 
> Further testing under screen says otherwise -- it seems to give me the
> tty number, not the virtual console number. Is there any way to figure
> out what virtual console I'm am in

I'm sure that there are all kinds of heuristics you could try, but
ultimately the question is meaningless.

E.g. you can start a screen session on one terminal (which may not be a
VC, but an xterm, ssh login, etc), detach it, attach it to a different
terminal, or even attach it to multiple terminals.

The child process only knows about its controlling terminal. If that
happens to be a pty slave, you could try looking for any processes
connected to the pty master. But you aren't guaranteeed to find any such
processes; if a process is running under a different account, you won't
be able to enumerate its descriptors. And you might find that the
master is owned by e.g. sshd, in which case there really isn't any way to
find out what's on the other end of the connection.

If the process happens to be part of a "screen" session, you can use
"screen -ls" to list sessions, and find out which terminal they are
attached to (although they might be detached, or they might be attached to
something other than a VC).

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


peppy

2009-11-30 Thread Johann Spies
After reading about peppy on Freshmeat I decided to try it out after
installing it using easy_install.  But:

$ peppy
Traceback (most recent call last):
  File "/usr/bin/peppy", line 5, in 
pkg_resources.run_script('peppy==0.13.2', 'peppy')
  File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 452, in 
run_script
self.require(requires)[0].run_script(script_name, ns)
  File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1179, in 
run_script
execfile(script_filename, namespace, namespace)
  File 
"/usr/lib/python2.5/site-packages/peppy-0.13.2-py2.5.egg/EGG-INFO/scripts/peppy",
 line 13, in 
import peppy.main
  File "/usr/lib/python2.5/site-packages/peppy-0.13.2-py2.5.egg/peppy/main.py", 
line 16, in 
from peppy.buffers import *
  File 
"/usr/lib/python2.5/site-packages/peppy-0.13.2-py2.5.egg/peppy/buffers.py", 
line 11, in 
from peppy.actions import *
  File 
"/usr/lib/python2.5/site-packages/peppy-0.13.2-py2.5.egg/peppy/actions/__init__.py",
 line 31, in 
from peppy.lib.multikey import KeyAccelerator
  File 
"/usr/lib/python2.5/site-packages/peppy-0.13.2-py2.5.egg/peppy/lib/multikey.py",
 line 120, in 
'C-': wx.ACCEL_CMD,
AttributeError: 'module' object has no attribute 'ACCEL_CMD'

This is on Debian squeeze.

How do I solve this?

Regards
Johann
-- 
Johann Spies  Telefoon: 021-808 4599
Informasietegnologie, Universiteit van Stellenbosch

 "Lo, children are an heritage of the LORD: and the  
  fruit of the womb is his reward."Psalms 127:3 
-- 
http://mail.python.org/mailman/listinfo/python-list


how to debug extended module?

2009-11-30 Thread junyoung
Hi, I am a newbie who want to implement a extend module to use native
python language with my own shared library.

to test wrapper library(extend module, name is 'test.so'), I created
some test-cases.

There are some errors what I couldn't figure our reasons.

ex)
SystemError: error return without exception set

...

so, I ran the ddd with python and then I set test.py as a argument of
it.

ex)
ddd python

in ddd
run with arguments : test.py


but in this situation, I couldn't step in my own shared library
(compiled as the debug mode).

Is there any clear way to debug my extend module(that it, debug shared
library)??
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python and vc numbers

2009-11-30 Thread Gregory Ewing

Daniel Dalton wrote:

I can't find a reliable way to
determine the current console number with python or any bash tool. When
I say console number, I mean the actual console number, not screen
window or device it is sending to or whatever.


You may be able to tell by looking at the DISPLAY
environment variable. Usually it has a form like

  localhost:X.Y

where X and Y are numbers identifying the display
device and screen.

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


Re: ANN: GMPY 1.11rc1 is available

2009-11-30 Thread Mensanator
On Nov 29, 9:04 pm, casevh  wrote:
> Everyone,
>
> I'm pleased to annouce that a new version of GMPY is available.
> GMPY is a wrapper for the MPIR or GMP multiple-precision
> arithmetic library. GMPY 1.11rc1 is available for download from:
>
> http://code.google.com/p/gmpy/
>
> In addition to support for Python 3.x, there are several new
> features in this release:
>
> - Even faster conversion to/from Python longs.
> - Performance improvements by reducing function overhead.
> - Performance improvements by improved caching.
> - Support for cdivmod, fdivmod, and tdivmod.
> - Unicode strings are accepted on Python 2.x and 3.x.
> - Fixed regression in GMPY 1.10 where True/False were no
>   longer recognized.
>
> Comments on provided binaries
>
> The 32-bit Windows installers were compiled with MinGW32 using MPIR
> 1.3.0rc3 and will automatically recognize the CPU type and use code
> optimized for the CPU at runtime. The 64-bit Windows installers were
> compiled Microsoft's SDK compilers using MPRI 1.3.0rc3. Detailed
> instructions are included if you want to compile your own binary.
>
> Future plans
>
> On releasing the GIL: I have compared releasing the GIL versus the
> multiprocessing module and the multiprocessing module offers better
> and more predictable performance for embarrassingly parallel tasks
> than releasing the GIL. If there are requests, I can add a compile-
> time option to enable threading support but it is unlikely to
> become the default.
>
> On mutable integers: The performance advantages of mutable integers
> appears to be 20% to 30% for some operations. I plan to add a new
> mutable integer type in the next release of GMPY. If you want to
> experiment with mutable integers now, GMPY can be compiled with
> mutable version of the standard 'mpz' type. Please see the file
> "mutable_mpz.txt" for more information.
>
> Please report any issues!

By lucky coincidence I happen to be working on a Python implementation
of Brent's Cycle Detection algorithm to locate large loop cycles in
3n+C of the Collatz conjecture. I had the algorithm worked up in pure
Python but needed to implement it using gmpy to do the heavy lifting
(due to the breakdown of my C version).

I am happy to report that my initial tests using version 1.11 seem to
be a big improvement:

## home, vista, python 3.1, gmpy 1.10
## i:   2
##f1: 101
##f2: 401
## C:   40501
##loop @:   29593
##found in: 0.000 sec
##len(sv) 88 determined in: 0.000 sec
##
## i:   3
##f1:1009
##f2:4001
## C: 4037009
##loop @:12799165
##found in: 0.000 sec
##len(sv) 76 determined in: 0.000 sec
##
## i:   4
##f1:   10007
##f2:   40009
## C:   400370063
##loop @:   933402925
##found in: 0.000 sec
##len(sv) 780 determined in: 0.000 sec
##
## i:   5
##f1:  13
##f2:  49
## C: 40002100027
##loop @:  13522904574967
##found in: 0.015 sec
##len(sv) 2233 determined in: 0.000 sec
##
## i:   6
##f1: 103
##f2: 437
## C:   449000111
##loop @:   1712218136639
##found in: 0.032 sec
##len(sv) 7789 determined in: 0.015 sec
##
## i:   7
##f1:1019
##f2:4003
## C: 4079057
##loop @:2519240916548647
##found in: 0.219 sec
##len(sv) 51270 determined in: 0.078 sec
##
## i:   8
##f1:   10007
##f2:   40009
## C:   400370063
##loop @:7032060392244193
##found in: 0.452 sec
##len(sv) 110238 determined in: 0.172 sec
##
## i:   9
##f1:  17
##f2:  47
## C: 40003500049
##loop @: 7486962189408734959
##found in: 3.276 sec
##len(sv) 668255 determined in: 1.014 sec
##
## i:  10
##f1:  

Re: python logging filters

2009-11-30 Thread Grimsqueaker
My logging behaves as I expect now and I have a better understanding
of how the module functions.
Thank you for taking the time to explain those points to me. :)

On Nov 30, 4:10 pm, Vinay Sajip  wrote:
> On Nov 30, 6:52 am, Grimsqueaker  wrote:
>
>
>
> > So would I be correct in saying that Filters apply only the the object
> > they are attached to and have no effect on how messages are propagated
> > through thelogginghierarchy? If this is the case my next question
> > would be: How can I affect whether or not a message is propagated
> > further up the tree?
>
> You are correct about how Filters work. To prevent propagation, use
> the propagate attribute, documented here:
>
> http://docs.python.org/library/logging.html#logger-objects
>
> Most times, you don't need to use this. For example, if you want
> events in the A hierarchy to go to one place and events in the B
> hierarchy to go to another place (e.g. two different log files), you
> just attach different handlers (e.g. two different FileHandlers) to
> loggers A and B. If you want a combined log as well, add an
> appropriate handler to the root logger.
>
> I find that things usually work OK if I just determine what handlers I
> need and attach them to the appropriate loggers, setting the levels on
> handlers and loggers appropriately. If I need filtering logic for a
> logger or handler which is more involved than just an integer
> threshold (which happens less often), I use Filters. Even less often,
> if I need to block events from a part of the logger hierarchy from
> bubbling upwards, then I use the propagate attribute.
>
> Regards,
>
> Vinay Sajip

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


Re: python logging filters

2009-11-30 Thread Grimsqueaker
My logging behaves as I expect now and I have a better understanding
of how the module functions.
Thank you for taking the time to explain those points to me. :)

On Nov 30, 4:10 pm, Vinay Sajip  wrote:
> On Nov 30, 6:52 am, Grimsqueaker  wrote:
>
>
>
> > So would I be correct in saying that Filters apply only the the object
> > they are attached to and have no effect on how messages are propagated
> > through thelogginghierarchy? If this is the case my next question
> > would be: How can I affect whether or not a message is propagated
> > further up the tree?
>
> You are correct about how Filters work. To prevent propagation, use
> the propagate attribute, documented here:
>
> http://docs.python.org/library/logging.html#logger-objects
>
> Most times, you don't need to use this. For example, if you want
> events in the A hierarchy to go to one place and events in the B
> hierarchy to go to another place (e.g. two different log files), you
> just attach different handlers (e.g. two different FileHandlers) to
> loggers A and B. If you want a combined log as well, add an
> appropriate handler to the root logger.
>
> I find that things usually work OK if I just determine what handlers I
> need and attach them to the appropriate loggers, setting the levels on
> handlers and loggers appropriately. If I need filtering logic for a
> logger or handler which is more involved than just an integer
> threshold (which happens less often), I use Filters. Even less often,
> if I need to block events from a part of the logger hierarchy from
> bubbling upwards, then I use the propagate attribute.
>
> Regards,
>
> Vinay Sajip

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


Re: python logging filters

2009-11-30 Thread Grimsqueaker
My logging behaves as I expect now and I have a better understanding
of how the module functions.
Thank you for taking the time to explain those points to me. :)

On Nov 30, 4:10 pm, Vinay Sajip  wrote:
> On Nov 30, 6:52 am, Grimsqueaker  wrote:
>
>
>
> > So would I be correct in saying that Filters apply only the the object
> > they are attached to and have no effect on how messages are propagated
> > through thelogginghierarchy? If this is the case my next question
> > would be: How can I affect whether or not a message is propagated
> > further up the tree?
>
> You are correct about how Filters work. To prevent propagation, use
> the propagate attribute, documented here:
>
> http://docs.python.org/library/logging.html#logger-objects
>
> Most times, you don't need to use this. For example, if you want
> events in the A hierarchy to go to one place and events in the B
> hierarchy to go to another place (e.g. two different log files), you
> just attach different handlers (e.g. two different FileHandlers) to
> loggers A and B. If you want a combined log as well, add an
> appropriate handler to the root logger.
>
> I find that things usually work OK if I just determine what handlers I
> need and attach them to the appropriate loggers, setting the levels on
> handlers and loggers appropriately. If I need filtering logic for a
> logger or handler which is more involved than just an integer
> threshold (which happens less often), I use Filters. Even less often,
> if I need to block events from a part of the logger hierarchy from
> bubbling upwards, then I use the propagate attribute.
>
> Regards,
>
> Vinay Sajip

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


Re: Variables with cross-module usage

2009-11-30 Thread Lie Ryan

On 12/1/2009 7:51 AM, Terry Reedy wrote:

In everyday life and natural languages, a single name can be used to
refer to multiple objects just by context without referring any
namespace.


Namespace are contexts. They were (re)invented in programming just to
make it easier to have single name could refer to different objects --
in different contexts. Names bound within a function are interpreted as
being within the default local context without explicitly referring to
it. Indeed, one cannot explicitly refer to the local namespace of
functions, only to a dict copy thereof.


Let's stop with the silly analogies.


 > Let's not start making analogism between nature and silicon.

There are several things wrong with this.

You meant 'analogies'.


No, I meant "analogism". My spellchecker lined that red, but I know what 
I meant. Let me define this word, which apparently is not (at least yet) 
in the dictionary:
- analogism: the way of thinking that analogy must be perfectly similar 
to the "real thing" in every single way, to the point of making grand 
and complex story that is even more complicated than the "real thing" 
itself.



I did not go into that counterclaim, but indeed, many people who program
in C, for instance, use C names as if they were object names instead of
location names (or location,increment tuple names). Sometimes they even
forget that they are really just location names. One too-common result
of that confusion has been buffer overruns and virus programs that
exploit them. These are impossible in Python.


"address names" and "object names", those are a good definition; stop at 
that. Any more layers of analogies, with boxes, with strings, with how 
human uses "name" in social life, or with how snakes align themselves 
with stars are much less useful than just learning how the "name" itself 
behave.


Let's stop teaching with excessive analogies, they just provide layers 
and layers of thinking that would confuse people when the analogy 
doesn't match the "real thing". Just learn how they behave, directly.


Analogy are fine to describe when first explaining how roughly something 
works, but don't expect things to be the same down to the details; and 
worse, don't make more analogies to cover up for the points the previous 
analogy doesn't cover.


Just stop the "analogism" [1]!

[1] there I used the word again.
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyArg_ParseTupleAndKeywords in Python3.1

2009-11-30 Thread casevh
On Nov 30, 2:18 pm, Joachim Dahl  wrote:
> I think that "C" encoding is what I need, however I run into an odd
> problem.
> If I use the following C code
>
> static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
> {
>   char a, b;
>   char *kwlist[] = {"a", "b", NULL};
>   if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
> &b))
>     return NULL;
>   ...
>
> then the following works:
>
> >>> foo('a')
> >>> foo('a','b')
> >>> foo(a='a',b='b')
>
> but the following fails:>>> foo(b='b')
>
> RuntimeError: impossible: 'CC'
>
> Is this error-message expected?

Nope. It appears to be a bug in Python. The format code 'C' is missing
in the switch statement in skipitem() in getargs.c. I added "case
'C': /* int */" after "case 'c': /* char */" and then example worked
for me.

I'll open a bug report.

casevh
>
> On Nov 30, 10:19 pm, casevh  wrote:
>
> > On Nov 30, 1:04 pm, Joachim Dahl  wrote:
>
> > > Obviously the name of the C function and the char variable cannot both
> > > be foo,
> > > so the C code should be:
>
> > > static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
> > > {
> > >   char foochar;
> > >   char *kwlist[] = {"foochar", NULL};
> > >   if (!PyArg_ParseTupleAndKeywords(args, kwrds, "c", kwlist,
> > > &foochar))
> > >     return NULL;
> > >   ...
>
> > > The question remains the same: why can't I pass a single character
> > > argument to this function under Python3.1?
>
> > > Thanks.
> > > Joachim
>
> > > On Nov 30, 9:52 pm, Joachim Dahl  wrote:
>
> > > > I am updating an extension module from Python2.6 to Python3.
>
> > > > I used to pass character codes to the extension module, for example, I
> > > > would write:
>
> > > > >>> foo('X')
>
> > > > with the corresponding C extension routine defined as follows:
> > > > static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
> > > > {
> > > >   char foo;
> > > >   char *kwlist[] = {"foo", NULL};
> > > >   if (!PyArg_ParseTupleAndKeywords(args, kwrds, "c", kwlist, &foo))
> > > >     return NULL;
> > > >   ...
>
> > > > In Python3.0 this also works, but in Python3.1 I get the following
> > > > error:
> > > > TypeError: argument 1 must be a byte string of length 1, not str
>
> > > > and I seem to be supposed to write>>> foo(b'X')
>
> > > > instead. From the Python C API, I have not been able to explain this
> > > > new behavior.
> > > > What is the correct way to pass a single character argument to
> > > > Python3.1
> > > > extension modules?- Hide quoted text -
>
> > > - Show quoted text -
>
> > Python 3.1 uses "c" (lowercase c) to parse a single character from a
> > byte-string and uses "C" (uppercase c) to parse a single character
> > from a Unicode string. I don't think there is an easy way to accept a
> > character from both.
>
> > HTH,
>
> > casevh
>
>

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


Re: Creating a local variable scope.

2009-11-30 Thread r0g
markolopa wrote:
> On Nov 30, 4:46 am, Dave Angel  wrote:
>> markolopa wrote:

>> or
>> whether you accidentally reused the same name without giving it a new
>> value in the new loop.  
> 
> That is what I do regularly...8->
> 



Well really dude, you need to stop doing that. It's not a language
problem, it's a memory problem (human not RAM!). You need to be aware of
what you're putting into your namespace. This is one of the reasons
people try to avoid using global variables, if you forget you've used a
variable name and use it again somewhere you get an undefined state and
hours of debugging / data loss / subtle corruptions you won't spot until
 the backups have all been cycled etc.

I'm surprised you have a recurring problem with this really. My memory
is terrible and I reuse variable names all over the place without any
trouble. Maybe try keeping the length of your functions down so that
they fit on a single screen and create and use a strong naming
convention i.e.

Long, descriptive variable names all_in_lower_case
Function names all in CamelCase
Global names are in ALL CAPS
Loop variable names all prefixed with 'each_'

The details don't so much matter as long as you are consistent with it.
I'm sure many here would hate my coding conventions if they had to use
them but they seem to work OK for me and I can't recall ever having this
problem.


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


Re: Can't print Chinese to HTTP

2009-11-30 Thread Gnarlodious
> you probably need to change the encoding of sys.stdout
>>> sys.stdout.encoding
'UTF-8'

>> #!/usr/bin/python

> do you know what python version, exactly, that gets called by this
hashbang?
Verified in HTTP:
>>> print(sys.version)
3.1.1
Is is possible modules are getting loaded from my old Python?

I symlinked to the new Python, and no I do not want to roll it back
because it is work (meaning I would have to type "sudo").
ls /usr/bin/python
lrwxr-xr-x  1 root  wheel  63 Nov 20 21:24 /usr/bin/python -> /Library/
Frameworks/Python.framework/Versions/3.1/bin/python3.1
Ugh, I have not been able to program in 11 days.

Now I remember doing it that way because I could not figure out how to
get Apache to find the new Python.

ls /usr/local/bin/python3.1
lrwxr-xr-x  1 root  wheel  71 Nov 20 08:19 /usr/local/bin/python3.1 -
> ../../../Library/Frameworks/Python.framework/Versions/3.1/bin/
python3.1

So they are both pointing to the same Python.


And yes, I would prefer easier http scripting, but don't know one.

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


Re: Feature request: String-inferred names

2009-11-30 Thread The Music Guy
> Brad Harms FearsomeDragonfly at gmail.com
> Mon Nov 30 05:04:37 CET 2009
>
> That was a relatively simple example; classes as simple as the ones
> generated by the  It is more likely that the class generation could would
> appear in a metaclass's class constructor or decorator function, and there
> would be more than just the three attributes given.

Bwa ha ha! Well, I managed to screw up that paragraph pretty badly. (I
code better than I write, honest.) Let me try again:

That was a relatively simple example; classes as simple as the ones
generated by the factory function example given are not needed very
often. It is more likely that the class generation would appear in a
metaclass's class constructor or decorator function, and there would
be more than just the three attributes. That way it could be possible
to ADD those properties and methods to a class in the process of being
built rather than make a class with just those attributes.

Lie Ryan, I think I see what you're saying about using __dict__ to add
members to a class, but it's not quite the same. __dict__ is only for
attributes, NOT properties, methods, etc. which all come from the
class of an object rather than the object's __dict__. Adding things to
__dict__ would only work halfway; it wouldn't be very extensible.
That's (one of the reasons) why the members have to be accessed as
attributes rather than dict items.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bored.

2009-11-30 Thread Jorge Cardona
2009/11/30 Stef Mientki :
> Necronymouse wrote:
>>
>> Hello, I am learning python for about 2 years and I am bored. Not with
>> python but I have a little problem, when i want to write something I
>> realise that somebody had alredy written it! So i don´t want to make a
>> copy of something but i wanna get better in python skills. Don´t you
>> know what I should do?
>>
>>
>> ---sorry for my english, I ´m from czech rep...
>>
>
> Well I thought that after 2 years you would know every detail of a language
> ;-)
>
> A few ideas ( or better said the things that I'm still missing, and I guess
> every one can name a  few different ones )
> - PyJamas needs a lot of extensions
> - Simultanuous recording of  camera and sound (and preferable other signals)
> is completely missing
> - Rich editor or ( embedding of open office)
> - a system-wide mind mapper
> - graphical design package a la LabView

I had have a project in mind for several months, a compiler for
Modelica language in python, there is actually two main approach,
openmodelica and jmodelica, both free ( i don't remember the exactly
licences), openmodelica is written  in C++ and jmodelica has a
front-end for python, but its core is java based. I had started a
gtkmodelica project, in code google, with c++ and spirit library( i
didn't  find at the moment a good library like spirit in python), but
developing in c++ is quite slow (but is really nice), and recently I
found pyparsing, I think is a good tool for the parser, and i create a
repo in github (is empty right now), i wish i could have the enough
time right now, but i got a lot of work right now.

A project like this has a lot of great challenges: parsing,
differential equation solving, a lot about language semantics, the
graphical tool could be like labview, simulink, or maplesim ( I love
flowcanvas library for gtk in c++, but it is quite old  right now),
code generation (to use hardware in the loop), real time plotting,
etc... it could be a great project.

I'm using right now some python classes that works as wrapper for
openmodelica, and i use numpy for optimization purpose, and it works
great, but a more natural mix with a native python tool would be just
fantastic.

http://github.com/jorgeecardona/pymodelica
http://drobilla.net/software/flowcanvas/
http://code.google.com/p/gtkmodelica/
http://www.jmodelica.org/
http://www.ida.liu.se/~pelab/modelica/OpenModelica.html



>
> There's also a Python site, were projects are submitted that needs something
> ( some even pay a little),
> but I can't remember where it is :-(
>
> cheers,
> Stef
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Jorge Eduardo Cardona
jorgeecard...@gmail.com
jorgeecardona.blogspot.com

Linux registered user  #391186
Registered machine#291871

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


Re: [Edu-sig] teaching python using turtle module

2009-11-30 Thread kirby urner
On Mon, Nov 30, 2009 at 4:31 PM, Gregor Lingl  wrote:

<< fascinating code >>

>
> Hoping, you will find this a bit interesting,
> best regards
>
> Gregor
>

Really enlightening, both mathematically and from a coding point of
view.  I hadn't used turtle.py enough yet to know about the built-in
"context turtle" if you want to just say "forward" and forgo
specifying a target.  That's a nice Logo-ish touch.

Your take on the T is most excellent.

With your permission, I'd be happy to add both versions with
attribution to my online version of tmod.py for the benefit of future
students, and/or I could simply link to this post in the edu-sig
archives (why not both?).

Kirby


-- 
>>> from mars import math
http://www.wikieducator.org/Digital_Math
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Edu-sig] teaching python using turtle module

2009-11-30 Thread Gregor Lingl



kirby urner schrieb:

I'm glad turtle graphics intersected my thinking re extended precision
decimals (Decimal type) on edu-sig just now.

I've updated my tmods.py to contain a turtle rendering the plane-net of a T-mod:

http://www.4dsolutions.net/ocn/python/tmod.py (runnable source)
http://www.flickr.com/photos/17157...@n00/4147429781/  (GUI view)
  

Nice tiny app! Albeit not an example for using the if statement ;-)
Just to show you how turtle.py enables you to implement this
using quite different approaches to doing geometry, I'd like to add
two more implementations.

Besides you may notice that these do not rely on rather complicated
calculations of distances and angles, using the Pythagorean theorem
and trigonometrics but only on a few more fundamental properties of
the figure.

# Version 2 - using coordinate geometry without coordinates ;-)
# a different implementation for Kirby's "Plane Net for T-module"

from turtle import *
from math import sqrt

PHI = (sqrt(5)-1)/2

def planeNet(h=500): 
  setup(560,560)

  title("Plane Net for T-module")
  penup()
  back(h/2); left(90); back(h/2); right(90)
  pendown()

  forward(h); left(90)
  forward(h*PHI); A = pos(); forward(h-h*PHI); left(90)
  forward(h*PHI); B = pos(); forward(h-h*PHI); left(90)
  forward(h); C = pos()

  for P in A, B, C:
 goto(P)


# Version 3 - stamping simple transforms of the shape of
#  an isosceles rectangular triangle:

from turtle import Screen, Turtle
from math import sqrt

GOLDEN_RATIO = (sqrt(5)-1)/2

def planeNet(h=500.0, phi=GOLDEN_RATIO): 
  s = Screen(); s.setup(560,560); s.title("Plane Net for T-module")

  s.register_shape("recttriangle", ((0, 0), (h, 0), (0, h)))
  designer = Turtle(shape="recttriangle")
  designer.color("black","")
  designer.penup()
  designer.goto(-h/2, h/2)

  for width, height in ((1, 1-phi), (phi, 1-phi), (phi, 1)):
 designer.shapesize(width, height)
 designer.stamp()
 designer.forward(h)
 designer.right(90)
  designer.hideturtle()

Hoping, you will find this a bit interesting,
best regards

Gregor




Here's the graphical output:

http://www.flickr.com/photos/17157...@n00/4148139184/in/photostream/
(Python 3.1)

If you actually wanna fold the T, you need to snip off the cap and
reverse it, per this diagram:

http://www.rwgrayprojects.com/synergetics/s09/figs/f86515.html

120 of them, 60 folded left, 60 folded right, all of volume 1/24, make
the volume 5 rhombic triacontahedron.

http://www.rwgrayprojects.com/synergetics/s09/figs/f86419.html

If you blow up the volume by 3/2, to 7.5, the radius becomes phi /
sqrt(2) -- what we're showing with Decimals.

The reason this seems unfamiliar is the unit of volume is the
tetrahedron formed by any four equi-radiused balls in inter-tangency.

I'm spinning this as Martian Math these days, yakking on
math-thinking-l about it, learned it from Bucky Fuller, Dave Koski et
al.

Kirby

  

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


Re: Bored.

2009-11-30 Thread Ben Finney
geremy condra  writes:

> On Mon, Nov 30, 2009 at 5:14 PM, Necronymouse  wrote:
> > Hello, I am learning python for about 2 years and I am bored. Not
> > with python but I have a little problem, when i want to write
> > something I realise that somebody had alredy written it!

That's great news: it means you can learn by example, and also learn the
more important skills of collaborating with other developers.

> I'd find a big project and contribute to it. There's a lot more to
> being a developer than writing code, and its hard to learn much about
> that side of things by working on your own projects all the time.
> Plus, it can be very satisfying to make a widely used piece of
> software better.

This is good advice.

I would also say that it can be very satisfying contributing on a
*small* project: there is usually less communication overhead since
there are fewer people that need to communicate (the principles explored
in “The Mythical Man-Month”). On a small project, too, you can often
have a bigger impact which for many people is more satisfying.

So, in general: when you realise someone has already written something
you want to use, then start using it! You will quickly find that it
doesn't quite do everything you want, so that's your opportunity to make
improvements and start working with the existing developers.

-- 
 \“Always code as if the guy who ends up maintaining your code |
  `\ will be a violent psychopath who knows where you live.” —John |
_o__) F. Woods |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to prevent re.split() from removing part of string

2009-11-30 Thread MRAB

Jeremy wrote:

I am using re.split to... well, split a string into sections.  I want
to split when, following a new line, there are 4 or fewer spaces.  The
pattern I use is:

sections = re.split('\n\s{,4}[^\s]', lineoftext)

This splits appropriately but I lose the character matched by [^s].  I
know I can put parentheses around [^s] and keep the matched character,
but the character is placed in it's own element of the list instead of
with the rest of the lineoftext.

Does anyone know how I can accomplish this without losing the matched
character?


First of all, \s matches any character that's _whitespace_, such as
space, "\t", "\n", "\r", "\f". There's also \S, which matches any
character that's not whitespace.

But in answer to your question, use a look-ahead:

sections = re.split('\n {,4}(?=\S)', lineoftext)

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


Re: Bored.

2009-11-30 Thread Stef Mientki

John Bokma wrote:

Stef Mientki  wrote:

  
There's also a Python site, were projects are submitted that needs 
something ( some even pay a little),

but I can't remember where it is :-(



OP: A Python program to find it :D

  

that was the mind mapper I mentioned :-)

Stef

John
  


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


Re: Bored.

2009-11-30 Thread Tomasz Rola
Necronymouse wrote:
> Hello, I am learning python for about 2 years and I am bored. Not
> with python but I have a little problem, when i want to write
> something I realise that somebody had alredy written it! So i don´t
> want to make a copy of something but i wanna get better in python
> skills. Don´t you know what I should do?

In other words, you would like to be creative? If this is the case, you 
must let your head out of the box. People coding for too long have the 
tendency to have a box (say, a cube) on their heads. I think there is 
plenty of ideas waiting for someone to turn them into code. Look out the 
window. Read a book. Repeat.

Regards,
Tomasz Rola

--
** A C programmer asked whether computer had Buddha's nature.  **
** As the answer, master did "rm -rif" on the programmer's home**
** directory. And then the C programmer became enlightened...  **
** **
** Tomasz Rola  mailto:tomasz_r...@bigfoot.com **-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bored.

2009-11-30 Thread John Bokma
Stef Mientki  wrote:

> There's also a Python site, were projects are submitted that needs 
> something ( some even pay a little),
> but I can't remember where it is :-(

OP: A Python program to find it :D

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


Re: emacs, pdb, python3, ubuntu

2009-11-30 Thread John Bokma
"K. Richard Pixley"  wrote:

> Does anyone have this combination working?
> 
> And if so, which version of ubuntu and what did you have to do to get it 
> to work?

I run Ubuntu 8.10 and use Emacs to code Python (mostly 2.5.x but I've done 
some small Python 3). What has Emacs to do with it?

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


Re: Language and collaboration

2009-11-30 Thread Terry Reedy

Ben Finney wrote:

"Emanuele D'Arrigo"  writes:


Ultimately I certainly appreciate the ubiquity of English even though
in the interest of fairness and efficiency I'd prefer the role of
common language to be given to a constructed language, such as Ido.


I prefer Lojban http://www.lojban.org/> as being logically robust
while fully expressive, and sharing the Ido goal of avoiding
disadvantage to native speakers of any particular existing language.


Even though I an mative-English speaking and therefore advantaged with 
English becoming ubiquitous, I would not mind learning *one* artificial 
'natural' language. I even considered Esperanto at one point. But the 
advocates of such a lingua franca cannot seem to agree on which ;-).

(Ido? never heard of it before -- will check W.P).

tjr

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


Re: Bored.

2009-11-30 Thread Stef Mientki

Necronymouse wrote:

Hello, I am learning python for about 2 years and I am bored. Not with
python but I have a little problem, when i want to write something I
realise that somebody had alredy written it! So i don´t want to make a
copy of something but i wanna get better in python skills. Don´t you
know what I should do?


---sorry for my english, I ´m from czech rep...
  
Well I thought that after 2 years you would know every detail of a 
language ;-)


A few ideas ( or better said the things that I'm still missing, and I 
guess every one can name a  few different ones )

- PyJamas needs a lot of extensions
- Simultanuous recording of  camera and sound (and preferable other 
signals) is completely missing

- Rich editor or ( embedding of open office)
- a system-wide mind mapper
- graphical design package a la LabView

There's also a Python site, were projects are submitted that needs 
something ( some even pay a little),

but I can't remember where it is :-(

cheers,
Stef
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bored.

2009-11-30 Thread geremy condra
On Mon, Nov 30, 2009 at 5:14 PM, Necronymouse  wrote:
> Hello, I am learning python for about 2 years and I am bored. Not with
> python but I have a little problem, when i want to write something I
> realise that somebody had alredy written it! So i don´t want to make a
> copy of something but i wanna get better in python skills. Don´t you
> know what I should do?
>
>
> ---sorry for my english, I ´m from czech rep...

I'd find a big project and contribute to it. There's a lot more to
being a developer than writing code, and its hard to learn
much about that side of things by working on your own projects
all the time. Plus, it can be very satisfying to make a widely
used piece of software better.

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


emacs, pdb, python3, ubuntu

2009-11-30 Thread K. Richard Pixley

Does anyone have this combination working?

And if so, which version of ubuntu and what did you have to do to get it 
to work?


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


Re: Python PIL and Vista/Windows 7 .. show() not working ...

2009-11-30 Thread Terry Reedy

Esmail wrote:

On Nov 30, 4:37 pm, David Bolen  wrote:



If that's the issue, there are various ways around it.  You could
patch PIL itself (same function) to quote the filename when it is
constructing the command.  Alternatively, the tempfile module has a
tempdir global you could set to some other temporary directory before
using the show() function (or any other code using tempfile).

-- David


Thanks for the pointers David, this will give me some things to
investigate.
As for me, I'm a long time and regular Linux user with some XP tossed
in.
I use the PIL under XP at times, but this problem is happening to
someone
I know who is using both Vista and Windows and can't get the basic
thing
to work so I am trying to help. (I have access to a Win 7 VM for
testing
purposes at least).

If I find a work-around or fix or concrete cause I'll post. In the
meantime
if anyone has any other ideas or fixes/suggestions, please don't be
shy :-)


How about forget PIL's show and its automagic behavior.
Use PIL's image save to write the image to a nice, known location, such 
as C:/temp/pic.jgp -- nothing but alphanumerics + ':/.'

Next test how to run a known external viewer from a command window.
Then use os.system or subprocess to run it with the same command line.
Package the two lines as a myshow(params) function.

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


Re: Completely OT

2009-11-30 Thread geremy condra
On Mon, Nov 30, 2009 at 1:21 PM, Victor Subervi  wrote:
> On Mon, Nov 30, 2009 at 2:00 PM, inhahe  wrote:
>>
>> On Mon, Nov 30, 2009 at 12:58 PM, inhahe  wrote:
>> > On Mon, Nov 30, 2009 at 12:49 PM, Victor Subervi
>> >  wrote:
>> >>
>> >>
>> >> If I'm not mistaken, that won't help me actually print to screen the
>> >> user's
>> >> choices as he selects them, which in my application, is important.
>> >> Please
>> >> advise.
>> >> TIA,
>> >> V
>> >
>> >
>> > sure, that's where this part comes in:
>> >
>> > the javascript would populate the list for the colors the user selects
>> > (the easiest way would probably be to give the list an id and use
>> > getElementByID())
>> >
>> > so basically you'd define, e.g., an onClick="blah('red'); return true"
>> > within the red element's tag, and then define a function blah(x) that
>> > says
>> > getElementById("my_list_id").innerHtml += "" + x;
>> > and of course give your list textarea an id="my_list_id" attribute in
>> > the tag.
>> >
>> > that could be slightly wrong, my javascript's rusty
>> >
>>
>> also don't forget to sanitize the data you receive before committing
>> it to the database, or someone can hack the javascript and send an SQL
>> injection attack
>
> Good call! However, in my case I can put this all behind a firewall. It's
> only for the shop builder's use, and that's my client...whom I can track!
> But I presume this would entail doing searches for and eliminating all
> unnecessary characters, right?
> V

Don't homebrew these things, they're easy to screw up and disastrous
to get wrong. Also, if you're worried about how secure something
you've written is, you can give yourself a little peace of mind by
running over it with some of the standard script kiddie tools before
deployment. It'll at least give you the comfort of knowing that they
won't be able to autopwn you for a while.

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


Re: Questions about list-creation

2009-11-30 Thread Terry Reedy

Manuel Graune wrote:

in (most) python documentation the syntax "list()"
and "[]" is treated as being more or less the same
thing.


Untrue. List() and [] happen to both evaluate to the same thing, an 
empty list. But there is no reason to expect list() and 
[] to always evaluate to the same thing. The docs for list() 
calls and [] displays and comprehensions are quite different.


In particular, they clearly say that [x] interprets x as an item and 
creates a list with one item, x, while list(x) interprets x as an 
iterable, and creates a list with multiple items, the items of x. So. in 
particular, list([]) != [[]].



For example "help([])" and "help(list())" point
to the same documentation.


This has nothing to do with list(text) and [text]. [] evaluates to an 
instance that has no doc string, so help backs up to its class. Compare


>>> help(1)
Help on int object:
...

The alternative to to print nothing, which would not be very helpful.

Try

>>> help()
...
help> topics

and you will see that there is a topic LISTLITERALS, though not one for 
comprehensions or sets or even generators. The list of topics seems not 
to have been kept up to date.


Terry Jan Reedy

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


Re: Bored.

2009-11-30 Thread Jonathan Gardner
On Nov 30, 2:14 pm, Necronymouse  wrote:
> Hello, I am learning python for about 2 years and I am bored. Not with
> python but I have a little problem, when i want to write something I
> realise that somebody had alredy written it! So i don´t want to make a
> copy of something but i wanna get better in python skills. Don´t you
> know what I should do?
>

Generally, lower-level stuff is already written, but the web apps and
desktop apps that use those lower-level apps need to be written.

I suggest you pick up web dev or app dev in Python. There are a
variety of frameworks. Think of an app you'd like to see, find a
framework, and have fun.
-- 
http://mail.python.org/mailman/listinfo/python-list


PIL build error on Snow Leopard

2009-11-30 Thread Xiao
Hello,

I haven't fully understood the nuances in the difference between
Apple's system Python and MacPython. But I have just installed Python
2.6.4 from python.org. Now I'm trying to install a fresh downloaded
PIL 1.1.6 but couldn't.
python setup.py install gives:
lipo: can't open input file: /var/tmp//ccfwpQd6.out (No such file or
directory)
Everything worked fine on Apple's Python 2.6.1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: top-like behavior

2009-11-30 Thread Jonathan Haddad
Awesome. Thank you!

Jon

On Mon, Nov 30, 2009 at 4:57 PM, Tim Chase
 wrote:
>> Is there a specific library used for displaying up to date consoles in
>> the same way top behaves?
>
> From the last time a similar question was asked[1]:
>
> You might look at the sourcecode for "iotop"[2] which would make a good
> example (it's a "top"-like program written in Python, used for monitoring
> I/O transactions on a per-process basis)
>
>
> -tkc
>
>
> [1]
> http://www.mail-archive.com/python-list@python.org/msg234993.html
>
> [2]
> http://guichaz.free.fr/iotop/
>



-- 
Jonathan Haddad
http://www.rustyrazorblade.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bored.

2009-11-30 Thread MRAB

Necronymouse wrote:

Hello, I am learning python for about 2 years and I am bored. Not
with python but I have a little problem, when i want to write
something I realise that somebody had alredy written it! So i don´t
want to make a copy of something but i wanna get better in python
skills. Don´t you know what I should do?


Choose a project that you find interesting. It doesn't matter if someone
has already done something similar because you'll learn more by doing.

When you have something reasonable, compare it to the one that already
exists. Your approach might be better, but if it's not then you can
still see why it isn't and how you could improve.

This way, when you do something that no-one else has done before, you'll
have a better understanding of the language and how best to design and
implement your project.
--
http://mail.python.org/mailman/listinfo/python-list


Re: top-like behavior

2009-11-30 Thread Tim Chase

Is there a specific library used for displaying up to date consoles in
the same way top behaves?


From the last time a similar question was asked[1]:

You might look at the sourcecode for "iotop"[2] which would make 
a good example (it's a "top"-like program written in Python, used 
for monitoring I/O transactions on a per-process basis)



-tkc


[1]
http://www.mail-archive.com/python-list@python.org/msg234993.html

[2]
http://guichaz.free.fr/iotop/
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with lambda / closures

2009-11-30 Thread Terry Reedy

Benjamin Kaplan wrote:


I don't know if anyone considers python's incomplete implementation of
closures a "feature" but it's documented so it's not really a bug
either.


I believe Python's implementation of closures is quite complete in 3.x. 
In what way do you consider it otherwise? One just has to use the right 
syntax. Closures in Python are created by nested function definitions. 
Lambda expressions create functions just like def statements and are not 
closures and do not create closure unless nested within another function 
definition. Thinking otherwise is the OP's mistake.



I believe there is a trick with default arguments to get this
to work, but I don't use lambdas enough to remember it.


One can simulate closures by giving an un-nested function a default 
argument. This has nothing to do with whether the function is defined by 
a lambda expression or a def statement.


Terry Jan Reedy


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


Re: Python PIL and Vista/Windows 7 .. show() not working ...

2009-11-30 Thread Esmail
On Nov 30, 4:37 pm, David Bolen  wrote:
> Esmail  writes:
> > I dug around in the docs and found a named parameter that I can set
> > when I
> > call show.
>
> > Definition:     im.show(self, title=None, command=None)
>
> > I installed irfanview and specified it/its path in the parameter,
> > but that didn't work either. It's really quite puzzling in the
> > case of Vista since that's been around for quite a few years now.
>
> But I thought everyone was sticking their fingers in their ears and
> humming to try to forget Vista had been released, particularly now
> that Windows 7 is out :-)
>
> Perhaps there's an issue with the temporary file location.  I don't
> have a Vista system to test on, but the show() operation writes the
> image to a temporary file as returned by tempfile.mktemp(), and then
> passes the name on to the external viewer.  The viewing command is
> handed to os.system() with the filename embedded without any special
> quoting.  So if, for example, the temporary location has spaces or
> "interesting" characters, it probably won't get parsed properly.
>
> One easy debugging step is probably to add a print just before the
> os.system() call that views the image (bottom of _showxv function in
> Image.py in my copy of 1.1.6).  That way at least you'll know the
> exact command being used.
>
> If that's the issue, there are various ways around it.  You could
> patch PIL itself (same function) to quote the filename when it is
> constructing the command.  Alternatively, the tempfile module has a
> tempdir global you could set to some other temporary directory before
> using the show() function (or any other code using tempfile).
>
> -- David

Thanks for the pointers David, this will give me some things to
investigate.
As for me, I'm a long time and regular Linux user with some XP tossed
in.
I use the PIL under XP at times, but this problem is happening to
someone
I know who is using both Vista and Windows and can't get the basic
thing
to work so I am trying to help. (I have access to a Win 7 VM for
testing
purposes at least).

If I find a work-around or fix or concrete cause I'll post. In the
meantime
if anyone has any other ideas or fixes/suggestions, please don't be
shy :-)

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


Re: Trying to understand += better

2009-11-30 Thread Terry Reedy

Roy Smith wrote:
In article <4b0a01a...@dnews.tpgi.com.au>, Lie Ryan  
wrote:



The semantic of the in-place operator is something like:
x += y
becomes
x = x.__iadd__(y)


Except that the expression x is evaluated just once instead of twice.


thus
foo.bar += baz
becomes
foo.bar = foo.bar.__iadd__(baz)

So the call sequence is,
foo.__getattr__('bar') ==> x
x.__iadd__(baz) ==> y
foo.__setattr__('bar', y)


I don't get where the __setattr__() call comes from in this situation.


Augmented *ASSIGNMENT* is a type of assignment.

The dis module can be used to see what CPython does.
>>> from dis import dis
>>> def f():
 foo.bar += baz

>>> dis(f)
  2   0 LOAD_GLOBAL  0 (foo)
  3 DUP_TOP
  4 LOAD_ATTR1 (bar)
  7 LOAD_GLOBAL  2 (baz)
 10 INPLACE_ADD
 11 ROT_TWO
 12 STORE_ATTR   1 (bar)
...
This amounts to what Roy said, with x and y being temporary entries on 
the stack.


Terry Jan Reedy

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


How to prevent re.split() from removing part of string

2009-11-30 Thread Jeremy
I am using re.split to... well, split a string into sections.  I want
to split when, following a new line, there are 4 or fewer spaces.  The
pattern I use is:

sections = re.split('\n\s{,4}[^\s]', lineoftext)

This splits appropriately but I lose the character matched by [^s].  I
know I can put parentheses around [^s] and keep the matched character,
but the character is placed in it's own element of the list instead of
with the rest of the lineoftext.

Does anyone know how I can accomplish this without losing the matched
character?

Thanks,
Jeremy

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


Re: PyArg_ParseTupleAndKeywords in Python3.1

2009-11-30 Thread Joachim Dahl
I think that "C" encoding is what I need, however I run into an odd
problem.
If I use the following C code

static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
{
  char a, b;
  char *kwlist[] = {"a", "b", NULL};
  if (!PyArg_ParseTupleAndKeywords(args, kwrds, "|CC", kwlist, &a,
&b))
return NULL;
  ...

then the following works:
>>> foo('a')
>>> foo('a','b')
>>> foo(a='a',b='b')

but the following fails:
>>> foo(b='b')
RuntimeError: impossible: 'CC'

Is this error-message expected?

On Nov 30, 10:19 pm, casevh  wrote:
> On Nov 30, 1:04 pm, Joachim Dahl  wrote:
>
>
>
>
>
> > Obviously the name of the C function and the char variable cannot both
> > be foo,
> > so the C code should be:
>
> > static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
> > {
> >   char foochar;
> >   char *kwlist[] = {"foochar", NULL};
> >   if (!PyArg_ParseTupleAndKeywords(args, kwrds, "c", kwlist,
> > &foochar))
> >     return NULL;
> >   ...
>
> > The question remains the same: why can't I pass a single character
> > argument to this function under Python3.1?
>
> > Thanks.
> > Joachim
>
> > On Nov 30, 9:52 pm, Joachim Dahl  wrote:
>
> > > I am updating an extension module from Python2.6 to Python3.
>
> > > I used to pass character codes to the extension module, for example, I
> > > would write:
>
> > > >>> foo('X')
>
> > > with the corresponding C extension routine defined as follows:
> > > static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
> > > {
> > >   char foo;
> > >   char *kwlist[] = {"foo", NULL};
> > >   if (!PyArg_ParseTupleAndKeywords(args, kwrds, "c", kwlist, &foo))
> > >     return NULL;
> > >   ...
>
> > > In Python3.0 this also works, but in Python3.1 I get the following
> > > error:
> > > TypeError: argument 1 must be a byte string of length 1, not str
>
> > > and I seem to be supposed to write>>> foo(b'X')
>
> > > instead. From the Python C API, I have not been able to explain this
> > > new behavior.
> > > What is the correct way to pass a single character argument to
> > > Python3.1
> > > extension modules?- Hide quoted text -
>
> > - Show quoted text -
>
> Python 3.1 uses "c" (lowercase c) to parse a single character from a
> byte-string and uses "C" (uppercase c) to parse a single character
> from a Unicode string. I don't think there is an easy way to accept a
> character from both.
>
> HTH,
>
> casevh

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


Re: parsing json data

2009-11-30 Thread John Bokma
f...@mauve.rahul.net (Edward A. Falk) wrote:

> There's a json parsing library in 2.6.  (Sadly, 2.6 is not out for
> Ubuntu yet.)

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2

on Ubuntu 9.04

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


Language and collaboration (was: Python Statements/Keyword Localization)

2009-11-30 Thread Ben Finney
"Emanuele D'Arrigo"  writes:

> Ultimately I certainly appreciate the ubiquity of English even though
> in the interest of fairness and efficiency I'd prefer the role of
> common language to be given to a constructed language, such as Ido.

I prefer Lojban http://www.lojban.org/> as being logically robust
while fully expressive, and sharing the Ido goal of avoiding
disadvantage to native speakers of any particular existing language.

> But it doesn't take a particularly religious person to see that "do to
> others as you would want them do to you" tends to be a valid principle

Indeed, religion is entirely redundant to that principle: one of the
earliest independent expressions of that principle is from a quite
non-religious philosopher.

己所不欲、勿施于人。
(What is undesirable to you, do not do to others.)
—孔夫子 Confucius, 551 BCE – 479 BCE

I prefer this formulation, since it doesn't enjoin to *do* something to
others on the unproven assumption that someone else wants the same as me
:-)

-- 
 \   Moriarty: “Forty thousand million billion dollars? That money |
  `\must be worth a fortune!” —The Goon Show, _The Sale of |
_o__)   Manhattan_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: semantics of ** (unexpected/inconsistent?)

2009-11-30 Thread inhahe
On Mon, Nov 30, 2009 at 2:05 PM, Lie Ryan  wrote:
> On 12/1/2009 5:58 AM, inhahe wrote:
>>
>> i wasn't suggesting it as a feature for python, just pointing out why
>> it might seem counterintuitive.
>
> I'm interested, what do YOU (inhahe) think the result should be? Should both
> become -9 or both become 9. What was your expectation when you wrote that
> post?
> --
> http://mail.python.org/mailman/listinfo/python-list
>

i think the way it works currently is the sane way..pays respect to
the standard order of operations, doesn't have to do anything special
with x = -3, just treats it as an integer, and corresponds with normal
algebra.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Intro To Python Using Turtle Graphics

2009-11-30 Thread Terry Reedy

Lawrence D'Oliveiro wrote:

Done by Northland Polytechnic, available for download under CC-BY-NC-ND here
.


I have two problems with the presentation, which make things harder for 
the students than they should be.


First, the instructor has students edit code in an editor that cannot 
directly run the code. Save the file.  Click to a command window. Enter 
'python somefile.py'. Ugh. Python comes with IDLE. Let students use it. 
(Or some equivalent, but turtle works fine with IDLE.) Replace above 
with 'press F5'. If there is a SyntaxError, not uncommon for students, 
the edit window comes back with the cursor near the spot of the foul.


Within the code, the instructor does 'import turtle' followed by 
'turtle.up', turtle.move(x,y)', etc. for tens of lines. Ugh. Either 
'from turtle import *' (which turtle was designed for) or, if one does 
not like that, 'import turtle as t', some one can write 't.up', etc.


There is also a echo glitch in the audio when the video comes from the 
monitor, as opposed to the room camera.


Aside from the above, it seems like a decent intro presenting 
statements, names, conditional execution, repeated execution, and 
function encapsulation.


tjr

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


Re: Completely OT

2009-11-30 Thread inhahe
On Mon, Nov 30, 2009 at 2:17 PM, Lie Ryan  wrote:
> On 12/1/2009 5:00 AM, inhahe wrote:
>>
>> On Mon, Nov 30, 2009 at 12:58 PM, inhahe  wrote:
>>>
>>> On Mon, Nov 30, 2009 at 12:49 PM, Victor Subervi
>>>   wrote:


 If I'm not mistaken, that won't help me actually print to screen the
 user's
 choices as he selects them, which in my application, is important.
 Please
 advise.
>
> That's where Javascript kicks in. You only need to use the javascript to
> modify your document (visual effect); you won't need it to submit to the
> server (the real action).
>

Oh yes, good point - even though (if he were still going to go the
JavaScript route) he'd modify the textarea using javascript, a regular
submit button could be used because it'll submit the current contents
of that textarea all the same.

>>
>> also don't forget to sanitize the data you receive before committing
>> it to the database, or someone can hack the javascript and send an SQL
>> injection attack
>
> Or a XSS attack (Cross-site scripting). Basically, you want to check whether
> the string received by the server matches your own predefined list of colors
> before storing to the database.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Bored.

2009-11-30 Thread Necronymouse
Hello, I am learning python for about 2 years and I am bored. Not with
python but I have a little problem, when i want to write something I
realise that somebody had alredy written it! So i don´t want to make a
copy of something but i wanna get better in python skills. Don´t you
know what I should do?


---sorry for my english, I ´m from czech rep...
-- 
http://mail.python.org/mailman/listinfo/python-list


Characters in arithmetic expressions (was: semantics of ** (unexpected/inconsistent?))

2009-11-30 Thread Ben Finney
MRAB  writes:

> Most programming languages don't differentiate in text between the
> number "negative 3" and the expression "negated 3". APL does. The
> former is written as "¯3" (3 preceded by the overscore character) and
> the latter as "-3" (3 preceded by the minus sign).

Well, since we're talking about special characters: the ‘-’ that we find
on our keyboard is a hyphen (U+002D). A minus sign is ‘−’ (U+2212) and
is unlikely to be found on the keyboard unless it's a keyboard designed
specifically for APL :-)

-- 
 \   “A ‘No’ uttered from deepest conviction is better and greater |
  `\   than a ‘Yes’ merely uttered to please, or what is worse, to |
_o__)  avoid trouble.” —Mahatma Gandhi |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: top-like behavior

2009-11-30 Thread John Bokma
Jonathan Haddad  wrote:

> Is there a specific library used for displaying up to date consoles in
> the same way top behaves?

No experience but I am quite sure that curses behaves like that.

http://www.amk.ca/python/howto/curses/

via http://www.google.com/search?q=python%20curses

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


Re: os.remove() permission problem

2009-11-30 Thread Christian Heimes
Victor Subervi wrote:
> When I go into the python interpreter and execute that statement, it
> succeeds. What have I missed?

You are confusing the permissions of a Unix file system. In order to
create or a remove a file from a directory you need the x and w
permission to enter the directory (x) and to modify (w) the directory
entry.

Christian

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


Re: Running function from win32 dll

2009-11-30 Thread Terry Reedy

Nadav Chernin wrote:


I want to run function from win32 dll.
I used ctypes.windll.LoadLibrary to load the DLL.
But I don’t know how to select function and run it.


Which part of the Lib manual chapter did you not understand?


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


Re: Object Not Callable, float?

2009-11-30 Thread Terry Reedy

W. eWatson wrote:

I think I understand it, but how does one prevent it from happening, or 
know it's the cause? That msg I got?


Yes. The message 'x is not callable', where x is a name of something you 
expect to be callable (such as the builtin functions and classes), 
signals that x has been rebound to a non-callable object.


On the other hand, if x is something you know not to be callable, there 
there is either a typo -- yxz(3) instead of yzx[3] -- or a bug such as
expr(arg) where you expect expr to evaluate to a function but it does 
not.  Say yzx[3]('abc') where you think yxz is a list of functions, or 
yzx(3)('abc') where you expect yzx to return a function.


tjr

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


Re: PySerial and termios

2009-11-30 Thread Glazner
On Nov 30, 7:41 pm, Grant Edwards  wrote:
> On 2009-11-30, a b  wrote:
>
> > I have a pain in the a** problem with pyserial- it works 90%
> > of time but on the 10% of time it thorows and termios.error
> > exception with the value (5, 'Input/output error') and i
> > cannot get rid of it :(
>
> Sounds like faulty converter or a bug in the device driver to
> me.
>
> > The system works as follows:
> > A device sends out rs485 data -> rs485 to rs232 converter converts it -
> >> an rs232->usb cable attatched to a computer reads the data. Until
> > now it hasn't bothered me too much since it hasn't been a lot
> > of data (every time i get this exception i unload the pl2303
> > module from kernel, then reload it, open the com port
>
> Does that get rid of the error?  If so, then it's definitely a
> problem with the converter or device-driver.
>
> > and hope it won't happen soon). But now the amount of data is
> > getting bigger and the exceptions in the log are quite
> > bothering already so if anyone has a good idea what could
> > affect it i'd be very glad... oh and the settings for the port
> > opening are: self.ser = serial.Serial(self.port,
> > self.baudrate, rtscts=0, xonxoff=0, timeout=0)
>
> Unless you want to try to troubleshoot the device driver and
> USB traffic, the only suggestion I have is to try different
> converters and/or different versions of the driver.
>
> --
> Grant Edwards                   grante             Yow! If Robert Di Niro
>                                   at               assassinates Walter Slezak,
>                                visi.com            will Jodie Foster marry
>                                                    Bonzo??

Try to use Portmon to see if your data is sent correctly.(if not, then
its the cable/converter)
http://technet.microsoft.com/en-us/sysinternals/bb896644.aspx
or another port monitor tool for other OS.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python PIL and Vista/Windows 7 .. show() not working ...

2009-11-30 Thread David Bolen
Esmail  writes:

> I dug around in the docs and found a named parameter that I can set
> when I
> call show.
>
> Definition: im.show(self, title=None, command=None)
>
> I installed irfanview and specified it/its path in the parameter,
> but that didn't work either. It's really quite puzzling in the
> case of Vista since that's been around for quite a few years now.

But I thought everyone was sticking their fingers in their ears and
humming to try to forget Vista had been released, particularly now
that Windows 7 is out :-)

Perhaps there's an issue with the temporary file location.  I don't
have a Vista system to test on, but the show() operation writes the
image to a temporary file as returned by tempfile.mktemp(), and then
passes the name on to the external viewer.  The viewing command is
handed to os.system() with the filename embedded without any special
quoting.  So if, for example, the temporary location has spaces or
"interesting" characters, it probably won't get parsed properly.

One easy debugging step is probably to add a print just before the
os.system() call that views the image (bottom of _showxv function in
Image.py in my copy of 1.1.6).  That way at least you'll know the
exact command being used.

If that's the issue, there are various ways around it.  You could
patch PIL itself (same function) to quote the filename when it is
constructing the command.  Alternatively, the tempfile module has a
tempdir global you could set to some other temporary directory before
using the show() function (or any other code using tempfile).

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


Re: Feature request: String-inferred names

2009-11-30 Thread Terry Reedy

Brad Harms wrote:

Well, yes, the names would have to be determined at run time. That's 
what getattr and setattr do, except that that do it in the context of an 
object rather than the local scope. However, I was under the impression 
that python's mechanism for looking up local names was the same as the 
mechanism used to look up attributes because names and attributes seem 
to function pretty much the same way. This I assumed because of the 
functionality of the locals() and globals() functions, which seem to act 
like the __dict__ attribute on objects except that the work on the 
current scope.


The definition of locals() allows it to just be a dict *copy* of the 
local namespace, rather than the local namespace itself. Within 
functions, (at least for CPython, and probably for other 
implementations), locals() is just a copy, and changes to locals() are 
*not* propagated back to the local namespace. Within functions, local 
name 'lookup' has nothing to do with dict lookup. (It is more like list 
indexing.)



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


Re: [Edu-sig] teaching python using turtle module

2009-11-30 Thread Alf P. Steinbach

* Edward Cherlin:

On Sun, Nov 29, 2009 at 11:34, Brian Blais  wrote:


After a bit of playing, I realized that I couldn't think of many exaples
which use turtle with conditional structures (if- and while- statements),


Repeat is used much more often. but of course we can provide examples
of any behavior you like. I like to use the turtle to generate
sequences, where I can use a conditional to stop when the turtle would
go off the screen. Fibonacci numbers, for example, or exponentials.
Similarly for spirals of various types. Simple cases like those are
easy to do in TA, while more complex sequences could use Python. There
are several fractal examples using loops provided with Sugar on a
Stick, including variations on Siepinksi constructions, and the Koch
Snowflake.


In ch 2 of

  http://preview.tinyurl.com/ProgrammingBookP3>

I use a turtle-generated spiral as the first example of a while loop.

I haven't got that far yet with that chapter, but I halfway plan on including a 
turtle graphics solve-a-maze example, which would/will be an example of 
conditionals with the turtle as a kind of actor making decisions.




or
functions that return values, as opposed to "procedures" like:
def square(length):
forward(length)
right(90)
forward(length)
right(90)
forward(length)
right(90)
forward(length)
right(90)


Plotting a graph. Some examples of that in ch 2 of aforementioned URL.


Cheers & hth.,

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


top-like behavior

2009-11-30 Thread Jonathan Haddad
Is there a specific library used for displaying up to date consoles in
the same way top behaves?

Thanks in advance,
Jon
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyArg_ParseTupleAndKeywords in Python3.1

2009-11-30 Thread casevh
On Nov 30, 1:04 pm, Joachim Dahl  wrote:
> Obviously the name of the C function and the char variable cannot both
> be foo,
> so the C code should be:
>
> static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
> {
>   char foochar;
>   char *kwlist[] = {"foochar", NULL};
>   if (!PyArg_ParseTupleAndKeywords(args, kwrds, "c", kwlist,
> &foochar))
>     return NULL;
>   ...
>
> The question remains the same: why can't I pass a single character
> argument to this function under Python3.1?
>
> Thanks.
> Joachim
>
> On Nov 30, 9:52 pm, Joachim Dahl  wrote:
>
>
>
> > I am updating an extension module from Python2.6 to Python3.
>
> > I used to pass character codes to the extension module, for example, I
> > would write:
>
> > >>> foo('X')
>
> > with the corresponding C extension routine defined as follows:
> > static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
> > {
> >   char foo;
> >   char *kwlist[] = {"foo", NULL};
> >   if (!PyArg_ParseTupleAndKeywords(args, kwrds, "c", kwlist, &foo))
> >     return NULL;
> >   ...
>
> > In Python3.0 this also works, but in Python3.1 I get the following
> > error:
> > TypeError: argument 1 must be a byte string of length 1, not str
>
> > and I seem to be supposed to write>>> foo(b'X')
>
> > instead. From the Python C API, I have not been able to explain this
> > new behavior.
> > What is the correct way to pass a single character argument to
> > Python3.1
> > extension modules?- Hide quoted text -
>
> - Show quoted text -

Python 3.1 uses "c" (lowercase c) to parse a single character from a
byte-string and uses "C" (uppercase c) to parse a single character
from a Unicode string. I don't think there is an easy way to accept a
character from both.

HTH,

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


Re: parsing json data

2009-11-30 Thread Edward A. Falk
There's a json parsing library in 2.6.  (Sadly, 2.6 is not out for
Ubuntu yet.)

-- 
-Ed Falk, f...@despams.r.us.com
http://thespamdiaries.blogspot.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Programming Challenges for beginners?

2009-11-30 Thread Edward A. Falk
In article <09ea817f-57a9-44a6-b815-299ae3ce7...@x5g2000prf.googlegroups.com>,
alex23   wrote:
>On Nov 27, 1:24 pm, astral orange <457r0...@gmail.com> wrote:
>> I would like to test out what I know so far by solving programming
>> challenges.
>
>Project Euler can be a lot of fun: http://projecteuler.net/

Oooh, that *does* look like fun.

-- 
-Ed Falk, f...@despams.r.us.com
http://thespamdiaries.blogspot.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyArg_ParseTupleAndKeywords in Python3.1

2009-11-30 Thread Joachim Dahl
Obviously the name of the C function and the char variable cannot both
be foo,
so the C code should be:

static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
{
  char foochar;
  char *kwlist[] = {"foochar", NULL};
  if (!PyArg_ParseTupleAndKeywords(args, kwrds, "c", kwlist,
&foochar))
return NULL;
  ...


The question remains the same: why can't I pass a single character
argument to this function under Python3.1?

Thanks.
Joachim

On Nov 30, 9:52 pm, Joachim Dahl  wrote:
> I am updating an extension module from Python2.6 to Python3.
>
> I used to pass character codes to the extension module, for example, I
> would write:
>
> >>> foo('X')
>
> with the corresponding C extension routine defined as follows:
> static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
> {
>   char foo;
>   char *kwlist[] = {"foo", NULL};
>   if (!PyArg_ParseTupleAndKeywords(args, kwrds, "c", kwlist, &foo))
>     return NULL;
>   ...
>
> In Python3.0 this also works, but in Python3.1 I get the following
> error:
> TypeError: argument 1 must be a byte string of length 1, not str
>
> and I seem to be supposed to write>>> foo(b'X')
>
> instead. From the Python C API, I have not been able to explain this
> new behavior.
> What is the correct way to pass a single character argument to
> Python3.1
> extension modules?

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


PyArg_ParseTupleAndKeywords in Python3.1

2009-11-30 Thread Joachim Dahl
I am updating an extension module from Python2.6 to Python3.

I used to pass character codes to the extension module, for example, I
would write:
>>> foo('X')

with the corresponding C extension routine defined as follows:
static PyObject* foo(PyObject *self, PyObject *args, PyObject *kwrds)
{
  char foo;
  char *kwlist[] = {"foo", NULL};
  if (!PyArg_ParseTupleAndKeywords(args, kwrds, "c", kwlist, &foo))
return NULL;
  ...


In Python3.0 this also works, but in Python3.1 I get the following
error:
TypeError: argument 1 must be a byte string of length 1, not str

and I seem to be supposed to write
>>> foo(b'X')
instead. From the Python C API, I have not been able to explain this
new behavior.
What is the correct way to pass a single character argument to
Python3.1
extension modules?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Variables with cross-module usage

2009-11-30 Thread Terry Reedy

Lie Ryan wrote:

On 11/30/2009 12:00 PM, Terry Reedy wrote:

Dennis Lee Bieber wrote:


In these languages, the names always refer to the same location.
Python confuses matters by having names that don't really refer to
location, but are attached to the objects.


In everyday life and natural languages, names refer to people, other
objects, roles, and only occasionally to places that can be occupied. I
could claim that it is classical computer languages that confuse by
restricting names to locations in a linear sequence. You are just used
to the straightjacket ;-).


In everyday life and natural languages, though an object may have many 
names/aliases; once objects are assigned a name, it is practically 
impossible to change the name to the object the name will be practically 
stuck to it forever.


When children play tag, the role of It is rebound to another child every 
few seconds. When adults play conference, the role of Speaker or 
Presenter is rebound to another person a few times per hour.


In Python, it easy, perhaps too easy, to rebind built-in names, but it 
is usually a mistake. (Just yesterday there was a newbie post with that 
mistake.) It is common for global names to be bound just once 
(especially to functions and classes).


In both human life and programming performed by humans, the time scale 
of name rebinding varies tremendously. Not surprising really.


In everyday life and natural languages, a single 
name can be used to refer to multiple objects just by context without 
referring any namespace. 


Namespace are contexts. They were (re)invented in programming just to 
make it easier to have single name could refer to different objects -- 
in different contexts. Names bound within a function are interpreted as 
being within the default local context without explicitly referring to 
it. Indeed, one cannot explicitly refer to the local namespace of 
functions, only to a dict copy thereof.


> Let's not start making analogism between nature and silicon.

There are several things wrong with this.

You meant 'analogies'.

I will make them when I want to, which is when I think they are useful 
in providing new viewpoints and insight. They are one way to break out 
of straight-jacketed or boxed thinking. If you prefer your box, ignore me.


Silicon is a part of the natural world, and I was not making any such 
analogy. Python is an information processing and algorithm language, not 
a silicon programming language per se. And indeed, without a concept of 
'address', it is not very suited to that.


I *was* making an analogy between how we communicate informally about 
the natural and social worlds and how we communicate more formally about 
the abstract information world. Is it really surprising that we use the 
same psychological mechanisms? Silicon machine languages do not have 
names. And names, as used by humans, *are* the subject of discussion here.


Dennis clained that Python is confusing because it is not restricted to 
naming locations. I said I could claim instead that it is the 
restriction is confusing.


I did not go into that counterclaim, but indeed, many people who program 
in C, for instance, use C names as if they were object names instead of 
location names (or location,increment tuple names). Sometimes they even 
forget that they are really just location names. One too-common result 
of that confusion has been buffer overruns and virus programs that 
exploit them. These are impossible in Python.


To me, the virtue of Python is that it allows one to think and write in 
a relatively natural named-object model. Let the silicon-based 
interpreter then translate that to a named-sequential-location model, 
while avoiding the dangers thereof, even though it has the cost of 
slower execution.


Terry Jan Reedy

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


Re: [Edu-sig] teaching python using turtle module

2009-11-30 Thread kirby urner
I'm glad turtle graphics intersected my thinking re extended precision
decimals (Decimal type) on edu-sig just now.

I've updated my tmods.py to contain a turtle rendering the plane-net of a T-mod:

http://www.4dsolutions.net/ocn/python/tmod.py (runnable source)
http://www.flickr.com/photos/17157...@n00/4147429781/  (GUI view)

Here's the graphical output:

http://www.flickr.com/photos/17157...@n00/4148139184/in/photostream/
(Python 3.1)

If you actually wanna fold the T, you need to snip off the cap and
reverse it, per this diagram:

http://www.rwgrayprojects.com/synergetics/s09/figs/f86515.html

120 of them, 60 folded left, 60 folded right, all of volume 1/24, make
the volume 5 rhombic triacontahedron.

http://www.rwgrayprojects.com/synergetics/s09/figs/f86419.html

If you blow up the volume by 3/2, to 7.5, the radius becomes phi /
sqrt(2) -- what we're showing with Decimals.

The reason this seems unfamiliar is the unit of volume is the
tetrahedron formed by any four equi-radiused balls in inter-tangency.

I'm spinning this as Martian Math these days, yakking on
math-thinking-l about it, learned it from Bucky Fuller, Dave Koski et
al.

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


Re: os.remove() permission problem

2009-11-30 Thread Martijn Arts
On Mon, Nov 30, 2009 at 8:21 PM, Victor Subervi wrote:

> Hi;
> I get the following error when I try
> os.remove(file)
>
> *OSError*: [Errno 13] Permission denied: 'particulars.py'
>   args = (13, 'Permission denied')
>   errno = 13
>   filename = 'particulars.py'
>   strerror = 'Permission denied'
>
> Here are the permissions:
>
> -rwxr-xr-x  1 root root   455 Nov 28 05:58 particulars.py
>

Try chmodding the file to 755.


> When I go into the python interpreter and execute that statement, it
> succeeds. What have I missed?
> TIA,
> Victor
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python PIL and Vista/Windows 7 .. show() not working ...

2009-11-30 Thread Esmail
On Nov 30, 3:08 pm, Lie Ryan  wrote:
>
> What's your default image viewer? im.show is intended to be for
> debugging purpose and may always guaranteed to work if your image viewer
> doesn't support receiving the file through  the image to the program>.


It's whatever the default windows viewer is :-) .. so if I double-
click on
the image in the filemanager it fires it up and shows it. This works
in XP and Windows 7 and Vista (ie double clicking on the image and
having it display).

I dug around in the docs and found a named parameter that I can set
when I
call show.

Definition: im.show(self, title=None, command=None)

I installed irfanview and specified it/its path in the parameter,
but that didn't work either. It's really quite puzzling in the
case of Vista since that's been around for quite a few years now.


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


Re: os.remove() permission problem

2009-11-30 Thread Victor Subervi
On Mon, Nov 30, 2009 at 3:21 PM, Victor Subervi wrote:

> Hi;
> I get the following error when I try
> os.remove(file)
>
> *OSError*: [Errno 13] Permission denied: 'particulars.py'
>   args = (13, 'Permission denied')
>   errno = 13
>   filename = 'particulars.py'
>   strerror = 'Permission denied'
>
> Here are the permissions:
>
> -rwxr-xr-x  1 root root   455 Nov 28 05:58 particulars.py
>
> When I go into the python interpreter and execute that statement, it
> succeeds. What have I missed?
>
> This is on a CentOS system. I've tried manipulating the mode to 666 and 777
but that didn't help at all. I do read from the file, then close it, but
I've tried deleting a file I don't read and come up with the same error.
TIA,
V
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Questions about list-creation

2009-11-30 Thread Luis Zarrabeitia
On Monday 30 November 2009 12:22:17 pm Manuel Graune wrote:
>
> when using local variables in list comprehensions, say
>
> a=[i for i in xrange(10)]
>
> the local variable is not destroyed afterwards:
[...]
> b=list(j for j in xrange(10))
>
> the local variable is destroyed after use:

Actually, [] and list() are not the same. For instance, list(1,2) rises an 
error, while [1,2] is the list with two elements.

The comprehension is just a syntactic contruct that allows you to simplify the 
creation of lists, while the list() "function" (it is a class, actually) 
receives an iterable object and returns a list.

What you seem to be confused about is the construct:

(j for j in xrange(10))

That is called a generator expression, and it is very similar to the list 
comprehension, except that it builds an iterator (instead of a list, i.e, the 
xrange(10) is not consumed until it is needed), and the loop variable 
doesn't "leak" outside.

When you do b=list(j for j in xrange(10)), you are actually doing

b=list((j for j in xrange(10)))

(note the extra set of parenthesis - python lets you ommit those), i.e, you 
are calling the list() "function" with a single argument, an iterable that 
contains all the elements of xrange(10). You could be calling

foobar(j for j in xrange(10))

instead.

And I think I lost my way... I'm sleepy. If I confused you, sorry... and if 
I'm helped you, thank you for letting me :D.

Cya.

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python PIL and Vista/Windows 7 .. show() not working ...

2009-11-30 Thread Lie Ryan

On 12/1/2009 5:04 AM, Esmail wrote:


   im = Image.open('c://mypic.jpg')


sorry, slip of the finger, there's only one forward slash
or you can use two backward slashes.

The problem isn't with opening it (I know it opens fine
since I can get its size attribute via im.size) - the show()
is the problem.



What's your default image viewer? im.show is intended to be for 
debugging purpose and may always guaranteed to work if your image viewer 
doesn't support receiving the file through the image to the program>.

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


Re: Questions about list-creation

2009-11-30 Thread Stephen Hansen
On Mon, Nov 30, 2009 at 9:22 AM, Manuel Graune wrote:

> in (most) python documentation the syntax "list()"
> and "[]" is treated as being more or less the same
> thing. For example "help([])" and "help(list())" point
> to the same documentation. Since there are at least
> two cases where this similarity is not the case, (see below)
> can someone explain the reasoning behind this and point to
> further / relevant documentation?
> (To clarify: I am not complaining about this, just asking.)
>

They -do- pretty much the same thing, but you can't quite treat them as two
forms which can be exchanged at a whim.

[] is the syntax for creating a list literal in source code. Its also the
syntax for list comprehensions. A list comprehension is an expression that
constructs a list all at once.

list() is a function (type/constructor/...) which accepts any iterable as an
argument (or None), and uses it to construct a list, returning it.

Those two things are very different, although in the end they both produce
lists: one is syntax, the other is a function which has to be called.

1.)
>
> when using local variables in list comprehensions, say
>
> a=[i for i in xrange(10)]
>
> the local variable is not destroyed afterwards:
>
> print "a",a
> print "i",i
>
> using the similar code
>

List comprehensions "leaked", as more of an implementation detail I believe
then anything else: in Python 3 it was removed, to better match generator
expressions (IIRC).


>
> b=list(j for j in xrange(10))
>
> the local variable is destroyed after use:
>
> print "b",b
> print "j",j
>
>
But see, this is something completely different.

(j for j in xrange(10))

is NOT a list comprehension. Its a generator comprehension. In the first
example with lists, you're using literal syntax to construct (all at once) a
list. In this, you're using literal syntax to construct a generator-- the
generator is then passed to the list function, which iterates over it and
constructs a list, returning when that generator is exhausted.

And generator comprehensions don't leak their variables (I can't remember if
that was an implementation detail or a deliberate design decision, but
eventually list comprehensions were made to match the behavior).



> and 2)
>
> a=list([])
>
> vs.
>
> b=[[]]
>

Those are also doing two completely different things: on the first, you are
using literal syntax to create an empty list. You are then passing this list
(which is an iterable) to the list function, telling it to make a list out
of that literal. It does so, which is in the end a (shallow) copy of the
first list you made.

The second, you are using literal syntax to create an empty list, and using
literal syntax to place that empty list inside another list.

You basically can't treat the two things as interchangable, because they're
different: one is syntax, one is a function. Both are ways to make lists.

HTH,

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


Re: semantics of ** (unexpected/inconsistent?)

2009-11-30 Thread Brian J Mingus
On Sun, Nov 29, 2009 at 5:58 PM, Esmail  wrote:

> Brian J Mingus wrote:
>
>>
>>
>>
>> I think you answered your own question. 3**2 comes first in the order of
>> operations, followed by the negation.
>>
>
> No, that's not the problem, I'm ok with the operator precedence of - vs **
>
> My problem is why I don't get the same result if I use the literal -3 or
> a variable that contains -3 (x in my example)


Yes, that is the problem. Setting x=-3 is the same as writing (-3)**2 vs.
-(3**2).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't print Chinese to HTTP

2009-11-30 Thread exarkun

On 05:05 pm, gnarlodi...@gmail.com wrote:

Thanks for the help, but it doesn't work. All I get is an error like:

UnicodeEncodeError: 'ascii' codec can't encode character '\\u0107' in
position 0: ordinal not in range(128)

It does work in Terminal interactively, after I import the sys module.
But my script doesn't act the same. Here is my entire script:

#!/usr/bin/python
print("Content-type:text/plain;charset=utf-8\n\n")
import sys
sys.stdout.buffer.write('f49\n'.encode("utf-8"))

All I get is the despised "Internal Server Error" with Console
reporting:

malformed header from script. Bad header=\xe6\x99\x89


As the error suggests, you're writing f49 to the headers section of the 
response.  This is because you're not ending the headers section with a 
blank line.  Lines in HTTP end with \r\n, not with just \n.


Have you considered using something with fewer sharp corners than CGI? 
You might find it more productive.


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


os.remove() permission problem

2009-11-30 Thread Victor Subervi
Hi;
I get the following error when I try
os.remove(file)

*OSError*: [Errno 13] Permission denied: 'particulars.py'
  args = (13, 'Permission denied')
  errno = 13
  filename = 'particulars.py'
  strerror = 'Permission denied'

Here are the permissions:

-rwxr-xr-x  1 root root   455 Nov 28 05:58 particulars.py

When I go into the python interpreter and execute that statement, it
succeeds. What have I missed?
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Completely OT

2009-11-30 Thread Lie Ryan

On 12/1/2009 5:00 AM, inhahe wrote:

On Mon, Nov 30, 2009 at 12:58 PM, inhahe  wrote:

On Mon, Nov 30, 2009 at 12:49 PM, Victor Subervi
  wrote:



If I'm not mistaken, that won't help me actually print to screen the user's
choices as he selects them, which in my application, is important. Please
advise.


That's where Javascript kicks in. You only need to use the javascript to 
modify your document (visual effect); you won't need it to submit to the 
server (the real action).




also don't forget to sanitize the data you receive before committing
it to the database, or someone can hack the javascript and send an SQL
injection attack


Or a XSS attack (Cross-site scripting). Basically, you want to check 
whether the string received by the server matches your own predefined 
list of colors before storing to the database.

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


Re: semantics of ** (unexpected/inconsistent?)

2009-11-30 Thread Lie Ryan

On 12/1/2009 5:58 AM, inhahe wrote:

i wasn't suggesting it as a feature for python, just pointing out why
it might seem counterintuitive.


I'm interested, what do YOU (inhahe) think the result should be? Should 
both become -9 or both become 9. What was your expectation when you 
wrote that post?

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


Re: how to format a python source file with tools?

2009-11-30 Thread Lie Ryan

On 12/1/2009 4:30 AM, Falcolas wrote:

Nonetheless, it would be better to implement coding standards that
everyone can stick to.


Agreed. You can't solve social issues with program.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python PIL and Vista/Windows 7 .. show() not working ...

2009-11-30 Thread Stephen Hansen
On Mon, Nov 30, 2009 at 9:57 AM, Esmail  wrote:

> Hello all.
>
> I am using the PIL 1.1.6 and Python 2.6.x under XP without any
> problems. However, I can't display any images under Vista
> or Windows 7. I could understand Windows 7 as it's relatively
> new, but Vista has been around for a bit.
>
> Sample code:
>
>  import Image
>
>  im = Image.open('c://mypic.jpg')
>  im.show()
>

Totally a guess, but did you try "c:\\mypic.jpg"?

\ is the path separator on windows, not /. A / will work in many situations,
but doubling it might cause problems perhaps (especially since you never
have to double forward-slashes, unlike back slashes)

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


Re: Can't print Chinese to HTTP

2009-11-30 Thread Ned Deily
In article 
,
 Gnarlodious  wrote:

> It does work in Terminal interactively, after I import the sys module.
> But my script doesn't act the same. Here is my entire script:
> 
> #!/usr/bin/python
> print("Content-type:text/plain;charset=utf-8\n\n")
> import sys
> sys.stdout.buffer.write('ùÁÄn'.encode("utf-8"))
> 
> All I get is the despised "Internal Server Error" with Console
> reporting:
> 
> malformed header from script. Bad header=Äxe6Äx99Äx89
> 
> Strangely, if I run the script in Terminal it acts as expected.
> 
> This is OSX 10.6 2,, Python 3.1.1.

Are you sure you are actually using Python 3?  /usr/bin/python is the 
path to the Apple-supplied python 2.6.1.  If you installed Python 3.1.1 
using the python.org OS X installer, the path should be 
/usr/local/bin/python3

-- 
 Ned Deily,
 n...@acm.org

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


Re: semantics of ** (unexpected/inconsistent?)

2009-11-30 Thread inhahe
On Mon, Nov 30, 2009 at 1:53 PM, Chris Rebert  wrote:
>> On Mon, Nov 30, 2009 at 3:46 AM, Gregory Ewing
>>  wrote:
>>> Esmail wrote:
>>>
 Wow .. never heard of Concatenative_languages languages before or the
 distinction you make. Your distinction explains the behavior, but I
 find it somewhat counter-intuitive.
>>>
>>> You shouldn't find it any more surprising than the fact that
>>>
>>>  a = 2 + 3
>>>  print a * 5
>>>
>>> gives a different result from
>>>
>>>  print 2 + 3 * 5
>
> On Mon, Nov 30, 2009 at 3:41 AM, inhahe  wrote:
>> one point of confusion could be the use of ** instead of superscript.
>> it might make things a little bit more counterintuitive-looking than
>> with superscripts, since the issue with
>
> Well, since source code is almost universally just plain ASCII and not
> in some file format with typesetting, superscripts aren't going to
> happen any time soon.
> (Also, avoid top-posting in the future.)
>

i wasn't suggesting it as a feature for python, just pointing out why
it might seem counterintuitive.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: High-performance Python websites

2009-11-30 Thread inhahe
On Wed, Nov 25, 2009 at 7:33 PM, ShoqulKutlu  wrote:
> Hi,
>
> Managing load of high volume of visitors is a common issue for all
> kind of web technologies. I mean this is not the python issue. This
> issue is mostly about server level designs. You need to supply load
> balancing for both web servers and databases to make your web site
> able to respond to several concurrent visitors. Of course a good
> programmed website is a key performance issue but for your mention I
> would also suggest considering how many hardwares, how many
> webservers, how many database cluster and which database server should
> be used or will be used in the future..
>

I don't know a lot about this issue, but take apache + php.  every
time a page is loaded a new instance of php  is loaded to run the
page, so i imagine load balancing can easiry be done on the page
request level by distributing instances of php processes.
whereas if you use python, you don't really want to load the python
interpreter for every page request.  as far as i can tell, the
canonical way is to have one app for the whole website that's
constantly running and  communicates with the server via WSGI.  or is
that wrong?  and wouldn't that make load balancing a little bit more
tricky, or at least different?  not sure..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: semantics of ** (unexpected/inconsistent?)

2009-11-30 Thread Chris Rebert
> On Mon, Nov 30, 2009 at 3:46 AM, Gregory Ewing
>  wrote:
>> Esmail wrote:
>>
>>> Wow .. never heard of Concatenative_languages languages before or the
>>> distinction you make. Your distinction explains the behavior, but I
>>> find it somewhat counter-intuitive.
>>
>> You shouldn't find it any more surprising than the fact that
>>
>>  a = 2 + 3
>>  print a * 5
>>
>> gives a different result from
>>
>>  print 2 + 3 * 5

On Mon, Nov 30, 2009 at 3:41 AM, inhahe  wrote:
> one point of confusion could be the use of ** instead of superscript.
> it might make things a little bit more counterintuitive-looking than
> with superscripts, since the issue with

Well, since source code is almost universally just plain ASCII and not
in some file format with typesetting, superscripts aren't going to
happen any time soon.
(Also, avoid top-posting in the future.)

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiprocessing.connection with ssl

2009-11-30 Thread Ned Deily
In article 
<8ff1698c-8205-4171-9e41-2e382bd52...@g23g2000vbr.googlegroups.com>,
 Xavier  wrote:
> I've hacked multiprocessing.connection (in a basic way) to allow ssl
> encryption using ssl.wrap_socket.
> 
> Anybody knows how i can contribute this to main developers?

If you haven't already, open a feature request issue on the Python bug  
tracker (http://bugs.python.org/) and attach the code as a patch file.

-- 
 Ned Deily,
 n...@acm.org

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


Re: Completely OT

2009-11-30 Thread Victor Subervi
On Mon, Nov 30, 2009 at 2:37 PM, inhahe  wrote:

> On Mon, Nov 30, 2009 at 1:21 PM, Victor Subervi 
> wrote:
> > On Mon, Nov 30, 2009 at 2:00 PM, inhahe  wrote:
> >>
> >> On Mon, Nov 30, 2009 at 12:58 PM, inhahe  wrote:
> >> > On Mon, Nov 30, 2009 at 12:49 PM, Victor Subervi
> >> >  wrote:
> >> >>
> >> >>
> >> >> If I'm not mistaken, that won't help me actually print to screen the
> >> >> user's
> >> >> choices as he selects them, which in my application, is important.
> >> >> Please
> >> >> advise.
> >> >> TIA,
> >> >> V
> >> >
> >> >
> >> > sure, that's where this part comes in:
> >> >
> >> > the javascript would populate the list for the colors the user selects
> >> > (the easiest way would probably be to give the list an id and use
> >> > getElementByID())
> >> >
> >> > so basically you'd define, e.g., an onClick="blah('red'); return true"
> >> > within the red element's tag, and then define a function blah(x) that
> >> > says
> >> > getElementById("my_list_id").innerHtml += "" + x;
> >> > and of course give your list textarea an id="my_list_id" attribute in
> >> > the tag.
> >> >
> >> > that could be slightly wrong, my javascript's rusty
> >> >
> >>
> >> also don't forget to sanitize the data you receive before committing
> >> it to the database, or someone can hack the javascript and send an SQL
> >> injection attack
> >
> > Good call! However, in my case I can put this all behind a firewall. It's
> > only for the shop builder's use, and that's my client...whom I can track!
> > But I presume this would entail doing searches for and eliminating all
> > unnecessary characters, right?
> > V
> >
>
> depends on if you're using python or php  on the server side
> if you're using Python, just use parameterized sql, which completely
> avoids the issue of sql injection
> if you're using php, parameterized sql is kind of pain in the ass, but
> it includes a function for sanitizing strings so you don't have to
> make one yourself.
> if i remember correctly though, my friend and i had issues with that
> function, for example ' would be saved as \' in our database, or
> something like that
> i'm not sure which characters you need to eliminate to sanitize sql
> parameters.. i wouldn't be comfortable relying on my own function to
> do that without thoroughly researching the issue... and i'd probably
> just rather find a function that's already been written
>

Yeah, parameterize it. PHP?! Wash your mouth out with soap!
;)
V
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Completely OT

2009-11-30 Thread inhahe
On Mon, Nov 30, 2009 at 1:21 PM, Victor Subervi  wrote:
> On Mon, Nov 30, 2009 at 2:00 PM, inhahe  wrote:
>>
>> On Mon, Nov 30, 2009 at 12:58 PM, inhahe  wrote:
>> > On Mon, Nov 30, 2009 at 12:49 PM, Victor Subervi
>> >  wrote:
>> >>
>> >>
>> >> If I'm not mistaken, that won't help me actually print to screen the
>> >> user's
>> >> choices as he selects them, which in my application, is important.
>> >> Please
>> >> advise.
>> >> TIA,
>> >> V
>> >
>> >
>> > sure, that's where this part comes in:
>> >
>> > the javascript would populate the list for the colors the user selects
>> > (the easiest way would probably be to give the list an id and use
>> > getElementByID())
>> >
>> > so basically you'd define, e.g., an onClick="blah('red'); return true"
>> > within the red element's tag, and then define a function blah(x) that
>> > says
>> > getElementById("my_list_id").innerHtml += "" + x;
>> > and of course give your list textarea an id="my_list_id" attribute in
>> > the tag.
>> >
>> > that could be slightly wrong, my javascript's rusty
>> >
>>
>> also don't forget to sanitize the data you receive before committing
>> it to the database, or someone can hack the javascript and send an SQL
>> injection attack
>
> Good call! However, in my case I can put this all behind a firewall. It's
> only for the shop builder's use, and that's my client...whom I can track!
> But I presume this would entail doing searches for and eliminating all
> unnecessary characters, right?
> V
>

depends on if you're using python or php  on the server side
if you're using Python, just use parameterized sql, which completely
avoids the issue of sql injection
if you're using php, parameterized sql is kind of pain in the ass, but
it includes a function for sanitizing strings so you don't have to
make one yourself.
if i remember correctly though, my friend and i had issues with that
function, for example ' would be saved as \' in our database, or
something like that
i'm not sure which characters you need to eliminate to sanitize sql
parameters.. i wouldn't be comfortable relying on my own function to
do that without thoroughly researching the issue... and i'd probably
just rather find a function that's already been written
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't print Chinese to HTTP

2009-11-30 Thread Lie Ryan

On 12/1/2009 4:05 AM, Gnarlodious wrote:

Thanks for the help, but it doesn't work. All I get is an error like:

UnicodeEncodeError: 'ascii' codec can't encode character '\\u0107' in
position 0: ordinal not in range(128)


The error says it all; you're trying to encode the chinese character 
using 'ascii' codec.


> malformed header from script. Bad header=\xe6\x99\x89

Hmmm... strange. The \xe6\x99\x89 happens to coincide with UTF-8 
representation of 晉. Why is your content becoming a header?



#!/usr/bin/python
do you know what python version, exactly, that gets called by this 
hashbang? You mentioned that you're using python 3, but I'm not sure 
that this hashbang will invoke python3 (unless Mac OSX has made a 
progress above other linux distros and made python 3 the default python).



Strangely, if I run the script in Terminal it acts as expected.


I think I see it now. You're invoking python3 in the terminal; but your 
server invokes python 2. Python 2 uses byte-based string literal, while 
python 3 uses unicode-based string literal. When you try to ' 
晉\n'.encode("utf-8"), python 2 tried to decode the string using 'ascii' 
decoder, causing the exception.

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


Re: reading from a text file

2009-11-30 Thread Tim Golden

inhahe wrote:

i don't understand the point of using 'with'
but i don't understand what 'with' does at all
i've tried to understand it a few times
anyway here:

import random
result = random.choice(open("c:\\test.txt").readlines())



Yep. That'll do the trick. The point of "with" is that,
while in CPython, an open file will be closed as soon
as it is out of scope -- in this case, after that line --
in other implementations of Python, this may not be so.
Good practice suggests using with (or try/finally) which
ensures that the file is closed, regardless of the implementation.

For a quick example it's not always easy to know whether
to include this kind of detail, but a with: block adds
very little noise and will save you from being caught out
somewhere, someday.

http://www.python.org/doc/current/whatsnew/2.6.html#pep-343-the-with-statement

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


Re: Questions about list-creation

2009-11-30 Thread inhahe
i should also mention that

a=[i for i in xrange(10)]

and

b=list(j for j in xrange(10))

isn't really just a difference of using [] vs. list()
the first case is a list comprehension, the second case is a generator
comprehension which is then converted to a list
(the bug only applies to list comprehensions, not generator comprehensions)

i.e. notice that you can do this
''.join(x for x in ['a','b','c'])
no list or [] involved - it's just a generator comprehension being
passed to a function.




On Mon, Nov 30, 2009 at 1:12 PM, inhahe  wrote:
> On Mon, Nov 30, 2009 at 12:22 PM, Manuel Graune  
> wrote:
>>
>> Hello,
>>
>> in (most) python documentation the syntax "list()"
>> and "[]" is treated as being more or less the same
>> thing. For example "help([])" and "help(list())" point
>> to the same documentation. Since there are at least
>> two cases where this similarity is not the case, (see below)
>> can someone explain the reasoning behind this and point to
>> further / relevant documentation?
>> (To clarify: I am not complaining about this, just asking.)
>>
>>
>> 1.)
>>
>> when using local variables in list comprehensions, say
>>
>> a=[i for i in xrange(10)]
>>
>> the local variable is not destroyed afterwards:
>>
>> print "a",a
>> print "i",i
>>
>> using the similar code
>>
>> b=list(j for j in xrange(10))
>>
>> the local variable is destroyed after use:
>>
>> print "b",b
>> print "j",j
>>
>
> I could be wrong, but I think this was actually a bug that was fixed later.
>
>> and 2)
>>
>> a=list([])
>>
>> vs.
>>
>> b=[[]]
>>
>
> those don't return the same thing
> list([]) will create a shallow copy of [], which will of course be []
>
> i can't think of a place where you'd want to use list() instead of [],
> but sometimes you might want to use 'list', such as in a defaultdict,
> in which case it's being used as a factory
>
>>
>> Regards,
>>
>> Manuel Graune
>>
>> --
>> A hundred men did the rational thing. The sum of those rational choices was
>> called panic. Neal Stephenson -- System of the world
>> http://www.graune.org/GnuPG_pubkey.asc
>> Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Questions about list-creation

2009-11-30 Thread Mel
Manuel Graune wrote:

> in (most) python documentation the syntax "list()"
> and "[]" is treated as being more or less the same
> thing. For example "help([])" and "help(list())" point
> to the same documentation. Since there are at least
> two cases where this similarity is not the case, (see below)
> can someone explain the reasoning behind this and point to
> further / relevant documentation?
> (To clarify: I am not complaining about this, just asking.)
> 
> 
> 1.)
> 
> when using local variables in list comprehensions, say
> 
> a=[i for i in xrange(10)]
> 
> the local variable is not destroyed afterwards:
> 
> print "a",a
> print "i",i

Long ago, lists were built using explicit code:

a = []
for i in xrange(10):
a.append (i)

which of course left i bound to the last value that was appended.

People decided later that this was wordier than it had to be, and could bury 
the real point of a computation under a lot of boilerplate code that 
initialized lists, so we got list comprehensions, as you note, and they 
behave the same as the original code.

> using the similar code
> 
> b=list(j for j in xrange(10))
> 
> the local variable is destroyed after use:

The list constructor is a lot more recent.  It takes any iterable as an 
argument and makes (or tries to make) a list with the resulting values.  The 
example you give takes a sequence comprehension as its argument.  A sequence 
comprehension doesn't create data values -- it creates a block of code that 
can be executed later to create data values, and it can be executed later in 
any context.  So we could also code (untested):

def S():
return (j for j in xrange (10))

def T(s):
return list (s)

c = S()
b = T(c)

which still creates a list, but at an astonishing remove.  The sequence 
comprehension `c` can't count on finding a `j` in the namespace it finally 
gets executed in, so it has to have it's own private namespace to use then.

That's why you don't see `j` in your local namespace when `list` finallty 
runs the sequence comprehension.

Mel.


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


Re: Completely OT

2009-11-30 Thread Victor Subervi
On Mon, Nov 30, 2009 at 1:35 PM, Dennis Lee Bieber wrote:

> On Mon, 30 Nov 2009 07:26:09 -0500, Victor Subervi
>  declaimed the following in
> gmane.comp.python.general:
>
> > Hi;
> > I need a recommendation. I want to print out data like this:
> >
> > blue
> > red
> >
>Why all the off-page links?
>
>How about just a table of checkboxes?
>
> 
>
>
>
>Blue
>
>
>
>
>Red
>
>
>
>
>
>
>
> 
>

Ya know, in the interest of time, why not. There are a couple of selection
lists that have a couple hundred elements each one, but heck, I need to move
on and not spend days on this. Thanks ;)
V
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Completely OT

2009-11-30 Thread Victor Subervi
On Mon, Nov 30, 2009 at 2:00 PM, inhahe  wrote:

> On Mon, Nov 30, 2009 at 12:58 PM, inhahe  wrote:
> > On Mon, Nov 30, 2009 at 12:49 PM, Victor Subervi
> >  wrote:
> >>
> >>
> >> If I'm not mistaken, that won't help me actually print to screen the
> user's
> >> choices as he selects them, which in my application, is important.
> Please
> >> advise.
> >> TIA,
> >> V
> >
> >
> > sure, that's where this part comes in:
> >
> > the javascript would populate the list for the colors the user selects
> > (the easiest way would probably be to give the list an id and use
> > getElementByID())
> >
> > so basically you'd define, e.g., an onClick="blah('red'); return true"
> > within the red element's tag, and then define a function blah(x) that
> > says
> > getElementById("my_list_id").innerHtml += "" + x;
> > and of course give your list textarea an id="my_list_id" attribute in the
> tag.
> >
> > that could be slightly wrong, my javascript's rusty
> >
>
> also don't forget to sanitize the data you receive before committing
> it to the database, or someone can hack the javascript and send an SQL
> injection attack
>

Good call! However, in my case I can put this all behind a firewall. It's
only for the shop builder's use, and that's my client...whom I can track!
But I presume this would entail doing searches for and eliminating all
unnecessary characters, right?
V
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Questions about list-creation

2009-11-30 Thread Lie Ryan

On 12/1/2009 4:22 AM, Manuel Graune wrote:


Hello,

in (most) python documentation the syntax "list()"
and "[]" is treated as being more or less the same
thing. For example "help([])" and "help(list())" point
to the same documentation. Since there are at least
two cases where this similarity is not the case, (see below)
can someone explain the reasoning behind this and point to
further / relevant documentation?
(To clarify: I am not complaining about this, just asking.)


1.)

when using local variables in list comprehensions, say

a=[i for i in xrange(10)]

the local variable is not destroyed afterwards:

print "a",a
print "i",i

using the similar code

b=list(j for j in xrange(10))

the local variable is destroyed after use:

print "b",b
print "j",j



It's not so much about list() vs. [] but generator comprehension vs. 
list comprehension. list() takes a generator comprehension, while 
[listcomp] is its own syntax. List comprehension leaked its "loop 
counter" to the surrounding namespace, while generator comprehension got 
its own tiny namespace.


This "bug" (or feature, depending on your political alignment) is fixed 
in Python 3.x:


Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
>>> a = [i for i in range(10)]
>>> i
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'i' is not defined
>>> a = list(i for i in range(10))
>>> i
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'i' is not defined
>>> ^Z

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


Re: Can't print Chinese to HTTP

2009-11-30 Thread Aahz
In article ,
Gnarlodious   wrote:
>
>Thanks for the help, but it doesn't work. All I get is an error like:
>
>UnicodeEncodeError: 'ascii' codec can't encode character '\\u0107' in
>position 0: ordinal not in range(128)

No time to give you more info, but you probably need to change the
encoding of sys.stdout.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

The best way to get information on Usenet is not to ask a question, but
to post the wrong information.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Questions about list-creation

2009-11-30 Thread inhahe
On Mon, Nov 30, 2009 at 12:22 PM, Manuel Graune  wrote:
>
> Hello,
>
> in (most) python documentation the syntax "list()"
> and "[]" is treated as being more or less the same
> thing. For example "help([])" and "help(list())" point
> to the same documentation. Since there are at least
> two cases where this similarity is not the case, (see below)
> can someone explain the reasoning behind this and point to
> further / relevant documentation?
> (To clarify: I am not complaining about this, just asking.)
>
>
> 1.)
>
> when using local variables in list comprehensions, say
>
> a=[i for i in xrange(10)]
>
> the local variable is not destroyed afterwards:
>
> print "a",a
> print "i",i
>
> using the similar code
>
> b=list(j for j in xrange(10))
>
> the local variable is destroyed after use:
>
> print "b",b
> print "j",j
>

I could be wrong, but I think this was actually a bug that was fixed later.

> and 2)
>
> a=list([])
>
> vs.
>
> b=[[]]
>

those don't return the same thing
list([]) will create a shallow copy of [], which will of course be []

i can't think of a place where you'd want to use list() instead of [],
but sometimes you might want to use 'list', such as in a defaultdict,
in which case it's being used as a factory

>
> Regards,
>
> Manuel Graune
>
> --
> A hundred men did the rational thing. The sum of those rational choices was
> called panic. Neal Stephenson -- System of the world
> http://www.graune.org/GnuPG_pubkey.asc
> Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Feature request: String-inferred names

2009-11-30 Thread Lie Ryan

On 12/1/2009 3:35 AM, Bruno Desthuilliers wrote:

Lie Ryan a écrit :

On 11/28/2009 3:08 PM, The Music Guy wrote:


(snip the part about the proposed feature - which I don't like but
that's not the point)


My
projects rely on a lot of metaclassing for the automatic generation of
properties and methods, which saves tremendous amounts of coding.


If you use it a lot, it is likely 1) you have abused class syntax for
what should have been a dict or 2) what you need is to override
__getattr__/__getattribute__ and __setattr__


I have to totally disagree here. The way the OP uses metaprogramming is
a really common and handy solution in lots of frameworks, and
drastically reduces the need for boilerplate (and the potential for
bugs). It's *WAY* cleaner (readability, introspection, doc etc) and far
less error-prone than going the __getattr(ibute)__ / __setattr__, and
also way more efficient (from execution time POV).


I won't argue with the usefulness of metaclass, I agree that metaclass 
is the cleanest way to implement certain things; but the main point is 
the OP's use of getattr/setattr while he got full control of the 
namespace dictionary.



Using __getattr__ and __setattr__ to emulate attributes (usually
descriptors) that can be built at class creation time is IMHO what
should be labeled as an "abuse" (at best).


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


Re: Python Statements/Keyword Localization

2009-11-30 Thread Emanuele D'Arrigo
Thank you all for the insights. I particularly like the broad spread
of opinions on the subject.

Indeed when I wrote the original post my thoughts were with those
young students of non-English speaking countries that start learning
to program before they learn English. My case is almost one of those:
I started at home when I was 13, toying around with Basic, and at the
time not only I didn't know English, but for a few more years I would
be learning only French. Later I did start learning English but I
still found that while learning programming in Pascal at school its
English keywords were somehow an interruption of my mental flow. At
the time (20 years ago) localization wasn't a particularly big thing
and this issue would have been a bit of a lost cause. But as the world
is becoming more and more interconnected I think it is important that
we all make an effort to respect cultural needs and sensitivities of
both non-western adults and youngsters alike.

Ultimately I certainly appreciate the ubiquity of English even though
in the interest of fairness and efficiency I'd prefer the role of
common language to be given to a constructed language, such as Ido.
But it doesn't take a particularly religious person to see that "do to
others as you would want them do to you" tends to be a valid
principle, and in the same way the world would be at a loss if an
Indian university came up with a wonderful programming language
available only in Sanskrit, the world is at a loss not having a
beautiful language such as Python natively available in other
scripts.

Again, thank you all!

Manu

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


Re: Python PIL and Vista/Windows 7 .. show() not working ...

2009-11-30 Thread Esmail
>
>   im = Image.open('c://mypic.jpg')

sorry, slip of the finger, there's only one forward slash
or you can use two backward slashes.

The problem isn't with opening it (I know it opens fine
since I can get its size attribute via im.size) - the show()
is the problem.

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


Re: semantics of ** (unexpected/inconsistent?)

2009-11-30 Thread MRAB

Lie Ryan wrote:

On 11/30/2009 12:38 PM, Esmail wrote:

Thanks all!! I get it now :-)

It helped to have a number of different explanations, thanks
for taking the time to post. Much appreciated.


I generally do not expect operator precedence to be reliable at all 
except for:


+ - (binary ops, not the unary)
* /
**

for other operators I would have explicit parens. It's too much work to 
remember the rest of the precedence sheet.


Most programming languages don't differentiate in text between the
number "negative 3" and the expression "negated 3". APL does. The former
is written as "¯3" (3 preceded by the overscore character) and the
latter as "-3" (3 preceded by the minus sign).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Completely OT

2009-11-30 Thread inhahe
On Mon, Nov 30, 2009 at 12:58 PM, inhahe  wrote:
> On Mon, Nov 30, 2009 at 12:49 PM, Victor Subervi
>  wrote:
>>
>>
>> If I'm not mistaken, that won't help me actually print to screen the user's
>> choices as he selects them, which in my application, is important. Please
>> advise.
>> TIA,
>> V
>
>
> sure, that's where this part comes in:
>
> the javascript would populate the list for the colors the user selects
> (the easiest way would probably be to give the list an id and use
> getElementByID())
>
> so basically you'd define, e.g., an onClick="blah('red'); return true"
> within the red element's tag, and then define a function blah(x) that
> says
> getElementById("my_list_id").innerHtml += "" + x;
> and of course give your list textarea an id="my_list_id" attribute in the tag.
>
> that could be slightly wrong, my javascript's rusty
>

also don't forget to sanitize the data you receive before committing
it to the database, or someone can hack the javascript and send an SQL
injection attack
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Noobie python shell question

2009-11-30 Thread John Posner

On Sun, 29 Nov 2009 22:03:09 -0500, tuxsun  wrote:


I've been working in the shell on and off all day, and need to see if
a function I defined earlier is defined in the current shell I'm
working in.

Is there a shell command to get of list of functions I've defined?



How about this:


##


python
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit  
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.


a,b,c = 1,2,3



def spam(): return None

...


def eggs(): return None

...


dir()
['__builtins__', '__doc__', '__name__', '__package__', 'a', 'b', 'c',  
'eggs', 'spam']



locals()
{'a': 1, 'c': 3, 'b': 2, 'spam': ,  
'__builtins__':  '__builtin__' (built-in)>, 'eggs': ,  
'__package__': None,

 '__name__': '__main__', '__doc__': None}


[name for name in locals() if callable(locals()[name])]

Traceback (most recent call last):
  File "", line 1, in 
RuntimeError: dictionary changed size during iteration


[name for name in locals() if callable(locals()[name])]

['spam', 'eggs']


##

To avoid the harmless RuntimeError, define "name" before using it in the  
list comprehension (the final expression) -- e.g.:


   name = 1


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


  1   2   3   >