Re: initialising a class by name

2009-01-13 Thread Chris Rebert
On Tue, Jan 13, 2009 at 11:49 PM, Krishnakant  wrote:
> On Tue, 2009-01-13 at 21:51 -0800, Chris Rebert wrote:
>> Assuming all the classes are in the same module as the main program:
>>
>> instance = vars()[class_name](args, to, init)
>>
> The classes are not in the same module.
> Every glade window is coupled with one py file (module) containing one
> class that has the events for the glade file.
> Inshort, there is one class in one module and they are all seperate.
>> Assuming the classes are all in the same module "mod", which is
>> separate from the main program:
>>
>> instance = getattr(mod, class_name)(args, to, init)
>>
> Can you explain the difference between getattr and var()?

getattr(x, 'y') <==> x.y

vars() gives a dict representing the current accessible variable
bindings (I should have instead recommended the related globals()
function)
globals() gives a dict representing the global variable bindings
For example:
#foo.py
class Foo(object):
#code here

Foo()
#same as
globals()['Foo']()
#end of file

Cheers,
Chris

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Paul Rubin
Carl Banks  writes:
> At GE there was no encapsulation in sight on any system I worked on.
> In fact, our engine simulation was a special-purpose object-oriented
> language with--get this--no private variables.  Some other systems I
> worked on didn't even use scoping, let alone encapsulation.

Where my officemate used to work, the simulation stuff was written in
Matlab, but the actual flight stuff was written in Ada.  I wonder
if GE did something similar.
--
http://mail.python.org/mailman/listinfo/python-list


Re: initialising a class by name

2009-01-13 Thread Steven D'Aprano
On Wed, 14 Jan 2009 11:16:58 +0530, Krishnakant wrote:

> hello all,
> I have a strange situation where I have to load initiate an instance of
> a class at run-time with the name given by the user from a dropdown
> list.

Not strange at all.

> Is this possible in python and how?

Of course. Just use a dispatch table. Use a dict to map user strings to 
classes:


>>> class Spam(object): pass
...
>>> class Ham(object): pass
...
>>> dispatch_table = {"Spam": Spam, "Ham": Ham}
>>> dispatch_table["Ham"]()
<__main__.Ham object at 0xb7ea2f8c>


The keys don't even have to be the name of the class, they can be 
whatever input your users can give:

>>> dispatch_table["Yummy meat-like product"] = Spam
>>> dispatch_table["Yummy meat-like product"]()
<__main__.Spam object at 0xb7ea2f6c>


You can even automate it:

>>> dispatch_table = {}
>>> for name in dir():
... obj = globals()[name]
... if type(obj) == type:
... dispatch_table[name] = obj
...
>>> dispatch_table
{'Ham': , 'Spam': }



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


Re: initialising a class by name

2009-01-13 Thread Krishnakant
On Tue, 2009-01-13 at 21:51 -0800, Chris Rebert wrote:
> Assuming all the classes are in the same module as the main program:
> 
> instance = vars()[class_name](args, to, init)
> 
The classes are not in the same module.
Every glade window is coupled with one py file (module) containing one
class that has the events for the glade file.
Inshort, there is one class in one module and they are all seperate.
> Assuming the classes are all in the same module "mod", which is
> separate from the main program:
> 
> instance = getattr(mod, class_name)(args, to, init)
> 
Can you explain the difference between getattr and var()?

> Cheers,
> Chris
> 
happy hacking.
Krishnakant.

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


Re: read string in bits

2009-01-13 Thread ts
On Jan 14, 3:32 pm, Chris Rebert  wrote:
> On Tue, Jan 13, 2009 at 11:21 PM, ts  wrote:
> > hi, is there a way to read a character/string into bits in python?
>
> > i understand that character is read in bytes. Do i have to write a
> > function to convert it myself into 1010101 or there is a library in
> > python that enable me to do that?
>
> It's not quite clear to me what you mean, but here are 2 guesses:
> - If you want to convert an ASCII character to its ASCII integer
> value, use ord()
> - If you want to convert an integer into a string of its base-2
> representation, use bin() [requires Python 2.6, I think]
>
> Cheers,
> Chris
>
> --
> Follow the path of the Iguana...http://rebertia.com

hi, bin() is what i'm looking for. But only python 2.4 is available to
me. Is there a replacement of bin() in python 2.4?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Steven D'Aprano
On Tue, 13 Jan 2009 20:17:08 -0800, Carl Banks wrote:

> On Jan 13, 9:50 pm, Carl Banks  wrote:
>> The cultural impact that would have on the community is far worse,
>> IMHO, than any short-sighted benefits like being able to catch an
>> accidental usage of an internal variable. Trust would be replaced by
>> mistrust, and programming in Python would go from a pleasant experience
>> to constant antagonism.
> 
> And I'll give you a perfect example:
> 
> XML-DOM versus ElementTree
> 
> XML-DOM is the sort of standard that is borne of a culture that values
> encapsulation, strict type safety, and so on.  It's the way it is
> because designers were allowed to distrust the user, and the culture
> said that it was good to distrust the user.  Consequently, the interface
> is a pain to use, with all kinds of boilerplate and iterator types and
> such.
> 
> ElementTree was borne out of an environment where implementors are
> forced to trust the user.  As a consequence it was free to create an
> interface that was natural and straightforward and pleasant to use,
> without having to be guarded.

Which is all well and good, but there are circumstances where you *don't* 
want to trust arbitrary parts of your code to change other parts of your 
code, for good reason. In other words, you don't always want to trust 
your users.

Forget copy protection and DRM. Think about the software controlling a 
radiation machine for cancer treatment, with a limit on the number of 
rads it fires at any one time. It would be disastrous for any arbitrary 
function in the machine's software to be able to mess with that limit, 
accidentally or deliberately. People will die if you get it wrong.

My attitude when programming in Python is to accept that if the caller 
passes an inappropriate argument to my function, my function may crash 
(raise an exception). That's the caller's responsibility. I can get away 
with this laissez faire attitude because I don't have to worry about my 
software crashing at the wrong time and causing a plane filled with 500 
nuns and orphans suddenly flip upside down and nose-dive into a mountain. 
Or the nuclear reactor to suddenly drop all the fuel rods into the core 
simultaneously. Sometimes "oh, just raise an exception and exit" is 
simply not good enough.

Security/safety and freedom/flexibility are sometimes in conflict. There 
are plenty of languages which enforce access. It is a good thing that 
Python allows more flexibility. That's why I use Python. The traditional 
answer to this "if you need Java, you know where to get it".

But, gosh darn it, wouldn't it be nice to program the critical parts of 
your code in "strict Python", and leave the rest as "trusting Python", 
instead of having to use Java for the lot just to get strictness in the 
critical parts? If only there was a way to do this, and ensure people 
won't abuse it.


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


Re: WebDAV client module

2009-01-13 Thread Vincent Gulinao
Um.. and I can't seem to find any sample code of it around.

Can anybody share a simple snippet of how to use it? I don't understand
what's URI in PutFile method is suppose to be.

TIA.

On Tue, Jan 13, 2009 at 8:03 PM, Vincent Gulinao
wrote:

> Kindly point me to a good WebDAV client module for Python. Looks like PyDav
> is popular, but it seems some of the modules used within were already
> deprecated.
>
> TIA.
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: are there some special about '\x1a' symbol

2009-01-13 Thread Steve Holden
Unknown wrote:
> On 2009-01-12, John Machin  wrote:
> 
>> I didn't think your question was stupid. Stupid was (a) CP/M recording
>> file size as number of 128-byte sectors, forcing the use of an in-band
>> EOF marker for text files (b) MS continuing to regard Ctrl-Z as an EOF
>> decades after people stopped writing Ctrl-Z at the end of text files.
> 
> I believe that "feature" was inherited by CP/M from DEC OSes
> (RSX-11 or RSTS-11). AFAICT, all of CP/M's file I/O API
> (including the FCB) was lifted almost directly from DEC's
> PDP-11 stuff, which probably copied it from PDP-8 stuff.
> 
> Perhaps in the early 60's somebody at DEC had a reason.  The
> really interesting thing is that we're still suffering because
> of it 40+ years later.
> 
I suspect this is probably a leftover from some paper tape data formats,
when it was easier to detect the end of a file with a sentinel byte than
it was to detect run-off as end of file. It could easily date back to
the PDP-8.

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

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Carl Banks
On Jan 13, 11:35 pm, "Russ P."  wrote:
> I suggest you call Boeing and tell them that encapsulation is more
> trouble than it's worth for their 787 flight software. But please
> don't do it if you ever wish to work for them, because you will be
> proving conclusively that you don't have a clue about the kind of
> software systems they produce.

That's funny. I worked for four years at a GE Aviation subcontractor
on their jet engine control software, so I think do I have a clue
about how flight control software systems work.

At GE there was no encapsulation in sight on any system I worked on.
In fact, our engine simulation was a special-purpose object-oriented
language with--get this--no private variables.  Some other systems I
worked on didn't even use scoping, let alone encapsulation.

Looks like my anecdote cancels out yours!  Got any more?


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


Re: read string in bits

2009-01-13 Thread Chris Rebert
On Tue, Jan 13, 2009 at 11:21 PM, ts  wrote:
> hi, is there a way to read a character/string into bits in python?
>
> i understand that character is read in bytes. Do i have to write a
> function to convert it myself into 1010101 or there is a library in
> python that enable me to do that?

It's not quite clear to me what you mean, but here are 2 guesses:
- If you want to convert an ASCII character to its ASCII integer
value, use ord()
- If you want to convert an integer into a string of its base-2
representation, use bin() [requires Python 2.6, I think]

Cheers,
Chris

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


Re: pep 8 constants

2009-01-13 Thread Brendan Miller
> FOO = 1
>
> def f(x=FOO):
>   ...
>
>
> Use this instead:
>
> def f(x=1):
>   ...


I tend to use constants as a means of avoiding the proliferation of
magic literals for maintenance reasons... Like say if your example of
FOO would have been used in 10 places. Maybe it is more pythonic to
simply denote such a thing as simply a normal variable? That doesn't
seem to give a hint that it shouldn't be assigned a second time.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Paul Rubin
"James Mills"  writes:
> Python is a dynamic object oriented language ...  (almost verbatim
> from the website). It is compiled to bytecode and run on a virtual
> machine.

1. There is nothing inherent about dynamic languages that prevents
them from being compiled.  There are compiled implementations of
Lisp and Scheme that beat the pants off of Python in performance.

2. There is also nothing inherent in a dynamic OO language that says
that class descriptors have to be mutable, any more than strings have
to be mutable (Python has immutable strings).  I agree that being able
to modify class descriptors at runtime is sometimes very useful.  The
feature shouldn't be eliminated from Python or else it wouldn't be
Python any more.  But those occasions are rare enough that having to
enable the feature by saying (e.g.) "@dynamic" before the class
definition doesn't seem like a problem, both for encapsulation
and because it can also improve performance.
--
http://mail.python.org/mailman/listinfo/python-list


read string in bits

2009-01-13 Thread ts
hi, is there a way to read a character/string into bits in python?

i understand that character is read in bytes. Do i have to write a
function to convert it myself into 1010101 or there is a library in
python that enable me to do that?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Steven D'Aprano
On Wed, 14 Jan 2009 15:25:38 +1000, James Mills wrote:

> On Wed, Jan 14, 2009 at 3:11 PM, Russ P.  wrote:
> (...)
> 
>>> Give me one use-case where you strictly require that members of an
>>> object be private and their access enforced as such ?
>>
>> You're kidding, right? Think about a ten-million line program being
>> developed by 100 developers.
> 
> No I"m sorry this is not a valid use-case.

Why not? Just saying it isn't doesn't make it not.




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


Re: urllib2 - 403 that _should_ not occur.

2009-01-13 Thread Steve Holden
ajaksu wrote:
> On Jan 13, 1:33 am, Philip Semanchuk  wrote:
>> I don't think I understand you clearly. Whether or not Google et al  
>> whitelist the Python UA isn't a Python issue, is it?
> 
> Hi, sorry for taking so long to reply :)
> 
> I imagine it's something akin to Firefox's 'Report broken website':
> evangelism.
> 
> IMHO, if the PSF *cough* Steve *cough*  or individual Python hackers
> can contact key sites (as Wikipedia, groups.google, etc.) the issue
> can be solved sooner.
> 
> Instead of waiting for each whitelist maintainer's to find out we have
> a new UA, go out and tell them. A template for such requests could
> help those inside e.g. Google to bring the issue to the attention of
> the whitelist admins. The community has lots of connections that could
> be useful to pass the message along, if only 'led by the nose' to
> achieve that :)
> 
> Hence, the suggestion to raise a bug.
> 
OK, but be aware that the PSF doesn't monitor the bugs looking for
actions to take on behalf of the Python user community. In fact we
aren't overtly "political" in this way at all. This doesn't mean it
wouldn't be useful for the PSF to get involved in this role; just that
right now it isn't, and a bug report probably isn't the best way to get
action.

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

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


Re: pep 8 constants

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 4:49 PM, Brendan Miller  wrote:
> PEP 8 doesn't mention anything about using all caps to indicate a constant.
>
> Is all caps meaning "don't reassign this var" a strong enough
> convention to not be considered violating good python style? I see a
> lot of people using it, but I also see a lot of people writing
> non-pythonic code... so I thought I'd see what the consensus is.

It may in fact be deliberate. As there really are no
such thing as constants in Python - clearly :)

However, on the rare occasion I need to define
a global variable in a module that gets used in
several places and is more or less used as a
standard configured value - I tend to use ALL CAPS.

Still I would avoid using this idiom altogether
and jsut stick with default values. For Example:

FOO = 1

def f(x=FOO):
   ...


Use this instead:

def f(x=1):
   ...

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 4:35 PM, Paul Rubin
<"http://phr.cx"@nospam.invalid> wrote:
> "James Mills"  writes:
>> Bare in mind also, that enfocing access control / policing as you
>> called it has a performance hit as the machine (the Python vm)
>> has to perform checks each time members of an object are accessed.
>
> It's the other way around.  If the compiler knows that you aren't
> creating new attributes on the fly, it can put them into fixed slots
> like a C struct, and method calls become ordinary function calls
> through a dispatch vector.

Paul I wasn't referring to static languages and
languages that are compiled to machine code such
as C, C++, etc.

Python is a dynamic object oriented language ...
(almost verbatim from the website). It is compiled
to bytecode and run on a virtual machine.

I don't really think it would be possible or
desirable to have strict access control (encapsulation)
in the core of python.

a) it would piss us all off.
b) it would greatly impact on the dynamic nature of python.

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


pep 8 constants

2009-01-13 Thread Brendan Miller
PEP 8 doesn't mention anything about using all caps to indicate a constant.

Is all caps meaning "don't reassign this var" a strong enough
convention to not be considered violating good python style? I see a
lot of people using it, but I also see a lot of people writing
non-pythonic code... so I thought I'd see what the consensus is.

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Paul Rubin
"James Mills"  writes:
> Bare in mind also, that enfocing access control / policing as you
> called it has a performance hit as the machine (the Python vm)
> has to perform checks each time members of an object are accessed.

It's the other way around.  If the compiler knows that you aren't
creating new attributes on the fly, it can put them into fixed slots
like a C struct, and method calls become ordinary function calls
through a dispatch vector.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 3:35 PM, Russ P.  wrote:
> You know what? The more I think about the kind of nonsense you and
> others are spouting here, the more annoyed I get. I will gladly agree
> that encapsulation may be more trouble than it's worth for small
> applications, maybe even some medium sized ones, but you and others
> here are making blanket proclamations that are just plain nonsense.
>
> I suggest you call Boeing and tell them that encapsulation is more
> trouble than it's worth for their 787 flight software. But please
> don't do it if you ever wish to work for them, because you will be
> proving conclusively that you don't have a clue about the kind of
> software systems they produce.
>
> I've wasted more than enough time with this nonsense.

I am 100% confident that those same systems could be
well written in a language such as Python and would very
likely end up being much smaller and more manageable.

I have a question for you:

All your arguments seem to lean towards size and the
importance of encapsulation. What is the largest system
you have worked on - that has been written entirely in Python ?

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 3:11 PM, Russ P.  wrote:
> I think you are the one who is confused. Part of the problem here is
> that the term "encapsulation" has at least two widely used meanings
> (in the context of programming). In one sense, it just means grouping
> data and methods together. In another sense, it means restricting the
> client's access to data or methods. Someone earlier on this thread
> tried to claim that the first meaning applies to OOP, but Wikipedia
> (and many other sources) say just the opposite.
>
> People here are trying to claim that the leading underscore
> conventions used with Python are essentially equivalent to
> encapsulation. That is nonsense, of course.
>
> Others are arguing against encapsulation altogether. That is a bit
> like being against locks or passwords because they create a lot of
> hassle. Now locks are not needed everywhere, of course, but certainly
> they have their place. But the point is that if you don't like
> encapsulation, then by definition you don't like OOP. You may like
> certain features of OOP, but you don't like it in general. That's
> about all their is to it.
>
> And by the way, please don't bring up the canard that I am some kind
> of OO zealot. I think OO is overrated, and I don't Java, in part
> because it forces everything to be OO. The issue here is not my
> personal opinion of OOP. This issue is one of widely accepted
> definitions within the OO community.

Russ:

1. Quit while you're ahead.
2. OOP is encapsulating data and functionality into a single grouping (object).
3. Other features more recently developed by OO languages such as
Polymorphism, Access Control (a type of encapsulation), Inheritance
and Multiple Inheritance are all irrelevant and OO languages either
implement all or a subset of these features and each do so
differently.

Fundamentally it all boils down to4 things (which all of you -
including you Russ - just completely miss the point):

READ
UPDATE
ADVANCE

These are the 3 operations of a Turing machine of which all
computer algorithms can be defined. We usually define a 4th operation
called HALT.

Now go ponder on that a while and come back and tell
me whether you think you really need such things as
Abstract Base Classes, Interfaces, Access Control,
Static Typing, and so on and so forth ...

>> Give me one use-case where you strictly require
>> that members of an object be private and their
>> access enforced as such ?
>
> You're kidding, right? Think about a ten-million line program being
> developed by 100 developers.

And what is your point exactly ? Like I said, this is _not_ a valid
use case. A language that implements all of the features descirbed
in academic texts on OOP will not help you build such a system
any faster.

I should also point out that building such a system in Python would
most likely result in 1/3 of the size in terms of LoC.

I should also point out that your numbers you pulled out of your
hat would require 22years of development time given the industry
standard of 5 LOC/hg per developer. Good luck with that.

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


Re: initialising a class by name

2009-01-13 Thread Chris Rebert
On Tue, Jan 13, 2009 at 9:46 PM, Krishnakant  wrote:
> hello all,
> I have a strange situation where I have to load initiate an instance of
> a class at run-time with the name given by the user from a dropdown
> list.
> Is this possible in python and how?
> To make things clear, let me give the real example.
> there is an inventory management system and products belong to different
> categories.
> There are predefined categories in the database and for each category
> there is a module which contains a class made out of pygtk.
> This means what class gets instantiated and displayed in the gui depends
> on the choice a user makes in the dropdown.
> Now, I could have created a list of if conditions for all the categories
> as in
> if categorySelection == "books":
>Books = BookForm()
>
> However this is a problem because when there will be more than 100
> categories there will be that many if conditions and this will make the
> code uggly.
> so my idea is to name the class exactly after the name of the category
> so that when the user selects a category that name is used to initialise
> the instance of that class.
> So is it possible to initialise an instance of a class given its name
> from a variable?
> thanks and

Assuming all the classes are in the same module as the main program:

instance = vars()[class_name](args, to, init)

Assuming the classes are all in the same module "mod", which is
separate from the main program:

instance = getattr(mod, class_name)(args, to, init)

Cheers,
Chris

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


initialising a class by name

2009-01-13 Thread Krishnakant
hello all,
I have a strange situation where I have to load initiate an instance of
a class at run-time with the name given by the user from a dropdown
list.
Is this possible in python and how?
To make things clear, let me give the real example.
there is an inventory management system and products belong to different
categories.
There are predefined categories in the database and for each category
there is a module which contains a class made out of pygtk.
This means what class gets instantiated and displayed in the gui depends
on the choice a user makes in the dropdown.
Now, I could have created a list of if conditions for all the categories
as in 
if categorySelection == "books":
Books = BookForm()

However this is a problem because when there will be more than 100
categories there will be that many if conditions and this will make the
code uggly.
so my idea is to name the class exactly after the name of the category
so that when the user selects a category that name is used to initialise
the instance of that class.
So is it possible to initialise an instance of a class given its name
from a variable?
thanks and 
Happy hacking.
Krishnakant. 

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Russ P.
On Jan 13, 7:50 pm, Carl Banks  wrote:

> You know what?  Computer science buzzwords mean jack squat to me.  I
> don't give a horse's tail whether some people label it a fundamental
> concept of object-oriented programming or not.  I think it's a bad
> thing.  And it's a bad thing for exactly the reason I said: it gives
> the library implementor the power to dictate to the user how they can
> and can't use the library.  The cultural impact that would have on the
> community is far worse, IMHO, than any short-sighted benefits like
> being able to catch an accidental usage of an internal variable.
> Trust would be replaced by mistrust, and programming in Python would
> go from a pleasant experience to constant antagonism.
>
> No thanks.  "Software engineering" be damned.  Python is better off
> the way it is.

You know what? The more I think about the kind of nonsense you and
others are spouting here, the more annoyed I get. I will gladly agree
that encapsulation may be more trouble than it's worth for small
applications, maybe even some medium sized ones, but you and others
here are making blanket proclamations that are just plain nonsense.

I suggest you call Boeing and tell them that encapsulation is more
trouble than it's worth for their 787 flight software. But please
don't do it if you ever wish to work for them, because you will be
proving conclusively that you don't have a clue about the kind of
software systems they produce.

I've wasted more than enough time with this nonsense.
--
http://mail.python.org/mailman/listinfo/python-list


Re: executing multiple functions in background simultaneously

2009-01-13 Thread Michele Simionato
On Jan 14, 2:02 am, Catherine Moroney
 wrote:
> Hello everybody,
>
> I know how to spawn a sub-process and then wait until it
> completes.  I'm wondering if I can do the same thing with
> a Python function.
>
> I would like to spawn off multiple instances of a function
> and run them simultaneously and then wait until they all complete.
> Currently I'm doing this by calling them as sub-processes
> executable from the command-line.  Is there a way of accomplishing
> the same thing without having to make command-line executables
> of the function call?
>
> I'm primarily concerned about code readability and ease of
> programming.  The code would look a lot prettier and be shorter
> to boot if I could spawn off function calls rather than
> subprocesses.
>
> Thanks for any advice,
>
> Catherine

There is an example explaining how to implement exactly
this use case in the documentation of my decorator module:
http://pypi.python.org/pypi/decorator/3.0.0#async
The Async decorator works both with threads and with multiprocessing.
Here is an example of printing from multiple processes
(it assumes you downloaded the tarball of the decorator
module, documentation.py is the file containing the documentation
and the Async decorator; it also assumes you have the multiprocessing
module):

$ cat example.py
import os, multiprocessing
from documentation import Async

async = Async(multiprocessing.Process)

@async
def print_msg():
  print 'hello from process %d' % os.getpid()

for i in range(3):
print_msg()

$ python example.py
hello from process 5903
hello from process 5904
hello from process 5905
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 3:11 PM, Russ P.  wrote:
(...)

>> Give me one use-case where you strictly require
>> that members of an object be private and their
>> access enforced as such ?
>
> You're kidding, right? Think about a ten-million line program being
> developed by 100 developers.

No I"m sorry this is not a valid use-case.

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Russ P.
On Jan 13, 7:32 pm, "James Mills" 
wrote:
> On Wed, Jan 14, 2009 at 1:18 PM, Russ P.  wrote:
> > Yes, but the fact that you can approximate OO programming in a
> > particular language does not make that language object oriented. You
> > can approximate OO programming in C, but that does not mean that C is
> > an OO language.
>
> Wrong. Not having strict and enforced access control 9_NOT_ encapsulation)
> (Please stop confusing the two) is not a strict requirements of the OO model.

I think you are the one who is confused. Part of the problem here is
that the term "encapsulation" has at least two widely used meanings
(in the context of programming). In one sense, it just means grouping
data and methods together. In another sense, it means restricting the
client's access to data or methods. Someone earlier on this thread
tried to claim that the first meaning applies to OOP, but Wikipedia
(and many other sources) say just the opposite.

People here are trying to claim that the leading underscore
conventions used with Python are essentially equivalent to
encapsulation. That is nonsense, of course.

Others are arguing against encapsulation altogether. That is a bit
like being against locks or passwords because they create a lot of
hassle. Now locks are not needed everywhere, of course, but certainly
they have their place. But the point is that if you don't like
encapsulation, then by definition you don't like OOP. You may like
certain features of OOP, but you don't like it in general. That's
about all their is to it.

And by the way, please don't bring up the canard that I am some kind
of OO zealot. I think OO is overrated, and I don't Java, in part
because it forces everything to be OO. The issue here is not my
personal opinion of OOP. This issue is one of widely accepted
definitions within the OO community.


> Remember that it is a model and not a strict set of requirements that
> programming
> languages must implement.

Of course it's not a "requirement that programming languages must
implement." It's only a requirement if they want to be OO languages.

> In fact, Python borrows features from the Functional Paradigm. Does this
> make it a Functional Language ? No. Why ? Because one of the clear
> requirements of the Functional Paradigm is that functions cannot have
> side affects.
>
> > So I can claim that Python is not strictly object oriented until it
> > gets encapsulation (in the sense of data hiding). That is simply a
> > fact, and no amount of pleading or obfuscation will change it.
>
> In fact this is true, C can be seen as an programming language
> that has features of the OO model.
>
> I think one of the things you guys are missing out
> here is that there are really only two Paradigms
> or Machines. Functional and Imperative. And guess
> what ? As it turns out we can implement functional
> machines that run on top of imperative ones!
>
> > Should Python get true encapsulation? I don't know. Maybe
> > encapsulation cannot be added without excessive overhead or without
> > compromising other more important aspects and features of the
> > language. But I do know that not having encapsulation is a limitation
> > to the use of Python for good software engineering. I may be in the
> > minority in the Python "community" on this one, but I am apparently in
> > the majority in the OO programming "community."
>
> Again, stop confusing terminology.
>
> Should Python get strict and enforce access control
> of object members ? No. Why ? I can think of several
> reasons.
>
> Give me one use-case where you strictly require
> that members of an object be private and their
> access enforced as such ?

You're kidding, right? Think about a ten-million line program being
developed by 100 developers.


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


Re: Standard IPC for Python?

2009-01-13 Thread Philip Semanchuk


On Jan 13, 2009, at 11:26 PM, drobi...@gmail.com wrote:


On Jan 13, 5:08 pm, Philip Semanchuk  wrote:

On Jan 13, 2009, at 4:31 PM, drobi...@gmail.com wrote:


On Jan 13, 2:37 pm, Philip Semanchuk  wrote:

I was suggesting getting posix_ipc or sysv_ipc to compile against a
compatibility library (Cygwin?) under Windows. It sounds like  
you're

proposing something totally different, no?



It's not really correct to call Cygwin a compatibility library. It's
more of a separate system.


Thanks for the education; I'm obviously not very familiar with it.

In any case, the current version (1.5.25) does not support  
sem_unlink
or shm_unlink so posix_ipc does not build. Cygwin 1.7, currently  
under

test, will support these.  I haven't tried it yet. I expect it will
work OOTB.


Thanks for the report. Strange that it supports the functions to open
but not close semaphores. IN any case, I'd be very happy if posix_ipc
or sysv_ipc would work with few or no modifications under Cygwin.

Cheers
Philip


I just downloaded cygwin 1.7 and posix_ipc builds successfully. The
demo appears to work.



Most excellent! Thank you for the good news.



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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread r
Here is a piece of C code this same guy showed me saying Pythonic
indention would make this hard to read -- Well lets see then!

I swear, before god, this is the exact code he showed me. If you don't
believe me i will post a link to the thread.

//  Warning ugly C code ahead!
if( is_opt_data() < sizeof( long double ) ) { // test for insufficient
data
return TRUE; // indicate buffer empty
  } // end test for insufficient data
  if( is_circ() ) { // test for circular buffer
if( i < o ) { // test for data area divided
  if( ( l - o ) > sizeof( long double ) ) { // test for data
contiguous
*t = ( ( long double * ) f )[ o ]; // return data
o += sizeof( long double ); // adjust out
if( o >= l ) { // test for out wrap around
  o = 0; // wrap out around limit
} // end test for out wrap around
  } else { // data not contiguous in buffer
return load( ( char * ) t, sizeof( long double ) ); // return
data
  } // end test for data contiguous
} else { // data are not divided
  *t = ( ( float * ) f )[ o ]; // return data
  o += sizeof( long double ); // adjust out
  if( o >= l ) { // test for out reached limit
o = 0; // wrap out around
  } // end test for out reached limit
} // end test for data area divided
  } else { // block buffer
*t = ( ( long double * ) f )[ o ]; // return data
o += sizeof( long double ); // adjust data pointer
  } // end test for circular buffer


if i where to write the same code in a 'Python style" it would look
like below. And personally i would never use that many comments in my
code. I normally in a situation as this one would only comment each
major conditional code block, and only if it contains code that is not
completely obvious. Commenting is important, but it *can* be over
done.

#-- Python Style --#
if is_opt_data() < sizeof(long double):
  return TRUE
  if is_circ():
if i < o: #test for data area divided
  if (l-o) > sizeof(long double): #test for data contiguous
*t = ( ( long double * ) f )[ o ]
o += sizeof( long double )
if o >= l:
  o = 0
  else: #data not contiguous in buffer
return load((char*) t, sizeof(long double))
else: #data are not divided
  *t = ((float*) f)[ o ]
  o += sizeof(long double)
  if o >= l: #test for out reached limit
o = 0
  else: #block buffer
*t = ((long double*) f)[ o ]
o += sizeof(long double)

WOW!, without all the braces, and over commenting,  i can actually
read this code now! Of course it would not run in C or Python but the
point here is readability. Python forged the path for all 21st century
languages. Get on board, or get on with your self.extinction() -- Your
Choice!

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Russ P.
On Jan 13, 7:50 pm, Carl Banks  wrote:
> On Jan 13, 6:45 pm, "Russ P."  wrote:
>
>
>
> > On Jan 13, 3:07 pm, Carl Banks  wrote:
>
> > > I've seen no evidence that any Python project is moving even remotely
> > > toward data encapsulation.  That would be a drastic change.  Even if
> > > it were only a minor change in the implementation (and it would not
> > > be), it would be a major stroke in the Python community.  It would
> > > basically cause a wholescale power shift from the user to the
> > > implementor.  As a user it'd be like the difference between living in
> > > a free democracy and a fascist dictatorship.
>
> > I just googled "object oriented principles." The first site that came
> > up lists four princicples:
>
> > - Encapsulation
> > - Abstraction
> > - Inheritance
> > - Polymorphism
>
> > The Wikipedia entry for "object-oriented programming" also lists
> > encapsulation as a "fundamental concept."
>
> > The first line on the python.org site says:
>
> > "Python is a dynamic object-oriented programming language that can be
> > used for many kinds of software development."
>
> > How can that possibly be true if you see "no evidence that any Python
> > project is moving even remotely toward data encapsulation"?
>
> Is this seriously your argument?  Python must be moving towards data
> encapsulation because there is a line in Python.org that, if you
> blindly accept the Wikipedia definition as truth, indirectly implies
> that it is?
>
> Are you *seriously* arguing this?

Did you read what I wrote? If so, you apparently didn't understand it.

> The argument is too ridiculous to deserve a refutation, so I'll just
> point out two things:
>
> 1. Wise people don't believe everything that is written on Wikipedia.

Nice try at diverting attention. The issue is not Wikipedia. As far as
I know, the definition of OOP given on Wikipedia is not controversial
-- at least not anywhere but here.

> 2. The person who wrote that line in Python.org is a wise person.

Oh, isn't that wonderful. Wow, I sure wish I was wise like that
person!

> > Semantics aside, I fail to understand your hostility toward a
> > fundamental concept of object-oriented programming. The difference
> > between a free democracy and a "fascist dictatorship"? Give me a
> > break!
>
> You know what?  Computer science buzzwords mean jack squat to me.  I
> don't give a horse's tail whether some people label it a fundamental
> concept of object-oriented programming or not.  I think it's a bad
> thing.  And it's a bad thing for exactly the reason I said: it gives
> the library implementor the power to dictate to the user how they can
> and can't use the library.  The cultural impact that would have on the
> community is far worse, IMHO, than any short-sighted benefits like
> being able to catch an accidental usage of an internal variable.
> Trust would be replaced by mistrust, and programming in Python would
> go from a pleasant experience to constant antagonism.
>
> No thanks.  "Software engineering" be damned.  Python is better off
> the way it is.

Now that's just classic. "We have Python and we don't need no stinkin'
software engineering." Well, you may not need it in your line of work,
but I need it in mine. In my line of work, Python is a tool, not a
religious faith.


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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Roy Smith
In article 
,
 "Russ P."  wrote:

> I can claim that Python is not strictly object oriented until it
> gets encapsulation (in the sense of data hiding). That is simply a
> fact, and no amount of pleading or obfuscation will change it.

I have no idea if Python is strictly anything.  What I do know is that it's 
a useful tool.  I'll take useful over OOO (Object Oriented Orthodoxy) any 
day.

People get all worked up over OO as if it were some kind of religion.  If I 
want religion, I'll go to shul.  What I want from a programming language is 
a tool that lets me get my work done.  If I transgress against some sacred 
tenet of OO religion, it is, as Rev. Dupas would say, all right.

Earlier in this thread, somebody (name elided to avoid me getting pegged 
for a indulging in a spelling flame):

> Bare in mind also, that enfocing access control / policing as you
> called it has a performance hit as the machine (the Python vm)
> has to perform checks each time members of an object are accessed.

All I can say to that is, "He who bares his mind, soon gets to the naked 
truth".
--
http://mail.python.org/mailman/listinfo/python-list


Re: Weird behaviour re: Python on Windows

2009-01-13 Thread Jerry Hill
On Tue, Jan 13, 2009 at 5:29 PM, Kevin Jing Qiu
 wrote:
> I've been experiencing weird behavior of Python's os module on Windows:
>
> Here's the environment:
> Box1: Running Windows 2003 Server with Apache+mod_python
> Box2: Running Windows 2003 Server with Zope/Plone and Z:\ mapped to D:\
> on Box1
>
> It appears any os calls that deals with file/dir on the mapped drive is
> problematic.

What user is this running as?  By any chance is it running as the
Local System user?  If so, that user has no network privileges,
including to mapped drives.

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


Re: Standard IPC for Python?

2009-01-13 Thread drobi...@gmail.com
On Jan 13, 5:08 pm, Philip Semanchuk  wrote:
> On Jan 13, 2009, at 4:31 PM, drobi...@gmail.com wrote:
>
> > On Jan 13, 2:37 pm, Philip Semanchuk  wrote:
> >> I was suggesting getting posix_ipc or sysv_ipc to compile against a
> >> compatibility library (Cygwin?) under Windows. It sounds like you're
> >> proposing something totally different, no?
>
> > It's not really correct to call Cygwin a compatibility library. It's
> > more of a separate system.
>
> Thanks for the education; I'm obviously not very familiar with it.
>
> > In any case, the current version (1.5.25) does not support sem_unlink
> > or shm_unlink so posix_ipc does not build. Cygwin 1.7, currently under
> > test, will support these.  I haven't tried it yet. I expect it will
> > work OOTB.
>
> Thanks for the report. Strange that it supports the functions to open  
> but not close semaphores. IN any case, I'd be very happy if posix_ipc  
> or sysv_ipc would work with few or no modifications under Cygwin.
>
> Cheers
> Philip

I just downloaded cygwin 1.7 and posix_ipc builds successfully. The
demo appears to work.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread r
On Jan 13, 9:50 pm, Carl Banks  wrote:
[snip]
it gives
> the library implementor the power to dictate to the user how they can
> and can't use the library.  The cultural impact that would have on the
> community is far worse, IMHO, than any short-sighted benefits like
> being able to catch an accidental usage of an internal variable.
> Trust would be replaced by mistrust, and programming in Python would
> go from a pleasant experience to constant antagonism.
[snip]
> Carl Banks

I agree, the second the Python interpretor say's NO! you cant do that
or i will wrap your knuckles! is the day i leave Python forever. I
hear C programmers complain all the time about Python saying; "Well, I
like in "C" that variable types must be declared because this keeps me
from making mistakes later" -- hog wash! Just learn to think in a
dynamic way and you will never have any problems. If you need a hand
holding language i guess Python is not for you. And don't forget, you
can learn a lot from your mistakes.

They are so brainwashed by this mumbo-jumbo, i see them do this all
the time...

int_count = 0
float_cost = 1.25
str_name = "Bob"

They can't think in a dynamic way because momma "C" has done it for
them for too long. "Eat your Peas and carrots now little C coder"  :D
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 1:50 PM, Carl Banks  wrote:
> 1. Wise people don't believe everything that is written on Wikipedia.
> 2. The person who wrote that line in Python.org is a wise person.

Agreed.

> You know what?  Computer science buzzwords mean jack squat to me.  I
> don't give a horse's tail whether some people label it a fundamental
> concept of object-oriented programming or not.  I think it's a bad
> thing.  And it's a bad thing for exactly the reason I said: it gives
> the library implementor the power to dictate to the user how they can
> and can't use the library.  The cultural impact that would have on the
> community is far worse, IMHO, than any short-sighted benefits like
> being able to catch an accidental usage of an internal variable.
> Trust would be replaced by mistrust, and programming in Python would
> go from a pleasant experience to constant antagonism.

+1

> No thanks.  "Software engineering" be damned.  Python is better off
> the way it is.

Python ihmo is one of the best engineered programming languages
and platform I have ever had the pleasure of working with
and continue to! :)

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Carl Banks
On Jan 13, 9:50 pm, Carl Banks  wrote:
> The cultural impact that would have on the
> community is far worse, IMHO, than any short-sighted benefits like
> being able to catch an accidental usage of an internal variable.
> Trust would be replaced by mistrust, and programming in Python would
> go from a pleasant experience to constant antagonism.

And I'll give you a perfect example:

XML-DOM versus ElementTree

XML-DOM is the sort of standard that is borne of a culture that values
encapsulation, strict type safety, and so on.  It's the way it is
because designers were allowed to distrust the user, and the culture
said that it was good to distrust the user.  Consequently, the
interface is a pain to use, with all kinds of boilerplate and iterator
types and such.

ElementTree was borne out of an environment where implementors are
forced to trust the user.  As a consequence it was free to create an
interface that was natural and straightforward and pleasant to use,
without having to be guarded.


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


Re: urllib2 - 403 that _should_ not occur.

2009-01-13 Thread Philip Semanchuk


On Jan 13, 2009, at 9:42 PM, ajaksu wrote:


On Jan 13, 1:33 am, Philip Semanchuk  wrote:

I don't think I understand you clearly. Whether or not Google et al
whitelist the Python UA isn't a Python issue, is it?


Hi, sorry for taking so long to reply :)

I imagine it's something akin to Firefox's 'Report broken website':
evangelism.

IMHO, if the PSF *cough* Steve *cough*  or individual Python hackers
can contact key sites (as Wikipedia, groups.google, etc.) the issue
can be solved sooner.

Instead of waiting for each whitelist maintainer's to find out we have
a new UA, go out and tell them. A template for such requests could
help those inside e.g. Google to bring the issue to the attention of
the whitelist admins. The community has lots of connections that could
be useful to pass the message along, if only 'led by the nose' to
achieve that :)

Hence, the suggestion to raise a bug.


Gotcha.

In this case I think there is no whitelist. I think Google has a  
default accept policy supplemented with a blacklist rather than a  
default ban policy mitigated by a whitelist. As evidence I submit the  
fact that my user agent of "funny fish" was accepted. In other words,  
Google has taken explicit steps to ban agents sending the default  
Python UA. Now, if the default UA changed in Python 3.0, maybe the  
best thing to do is keep quiet and maybe it will fly under the Google  
radar for a while. =)


Cheers
Philip



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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Carl Banks
On Jan 13, 6:45 pm, "Russ P."  wrote:
> On Jan 13, 3:07 pm, Carl Banks  wrote:
>
> > I've seen no evidence that any Python project is moving even remotely
> > toward data encapsulation.  That would be a drastic change.  Even if
> > it were only a minor change in the implementation (and it would not
> > be), it would be a major stroke in the Python community.  It would
> > basically cause a wholescale power shift from the user to the
> > implementor.  As a user it'd be like the difference between living in
> > a free democracy and a fascist dictatorship.
>
> I just googled "object oriented principles." The first site that came
> up lists four princicples:
>
> - Encapsulation
> - Abstraction
> - Inheritance
> - Polymorphism
>
> The Wikipedia entry for "object-oriented programming" also lists
> encapsulation as a "fundamental concept."
>
> The first line on the python.org site says:
>
> "Python is a dynamic object-oriented programming language that can be
> used for many kinds of software development."
>
> How can that possibly be true if you see "no evidence that any Python
> project is moving even remotely toward data encapsulation"?

Is this seriously your argument?  Python must be moving towards data
encapsulation because there is a line in Python.org that, if you
blindly accept the Wikipedia definition as truth, indirectly implies
that it is?

Are you *seriously* arguing this?

The argument is too ridiculous to deserve a refutation, so I'll just
point out two things:

1. Wise people don't believe everything that is written on Wikipedia.
2. The person who wrote that line in Python.org is a wise person.


> Semantics aside, I fail to understand your hostility toward a
> fundamental concept of object-oriented programming. The difference
> between a free democracy and a "fascist dictatorship"? Give me a
> break!

You know what?  Computer science buzzwords mean jack squat to me.  I
don't give a horse's tail whether some people label it a fundamental
concept of object-oriented programming or not.  I think it's a bad
thing.  And it's a bad thing for exactly the reason I said: it gives
the library implementor the power to dictate to the user how they can
and can't use the library.  The cultural impact that would have on the
community is far worse, IMHO, than any short-sighted benefits like
being able to catch an accidental usage of an internal variable.
Trust would be replaced by mistrust, and programming in Python would
go from a pleasant experience to constant antagonism.

No thanks.  "Software engineering" be damned.  Python is better off
the way it is.


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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 1:31 PM, r  wrote:
>> public = no leading underscore
>> private = one leading underscore
>> protected = two leading underscores
>>
>> Python uses encapsulation by convention rather than by enforcement.
>
> Very well said Terry!
>
> I like that python does not force me to do "everything" but does force
> things like parenthesis in a function/method call whether or not an
> argument is required/expected. This makes for very readable code.
> Visual parsing a Python file is very easy on the eyes due to this fact
> -- Thanks Guido! We do not need to add three new keywords when there
> is an accepted Pythonic way to handle public/private/protected

Agreed. Furthermore there very few cases where you need
to distinguish between whether an object's attribute is public
or private or even protected.

Consider the following two pieces of code and tell me
which is more Pythonic:

class A(object):

   def __init__(self):
  self.x = None

   def setX(self, v):
  self.x = v

   def getX(self):
  return self.x



class A(object):

   def __init__(self):
  self.x = None

I'll give you a hint ... It's the simpler one :)

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 1:25 PM, Rhodri James
 wrote:
> I wouldn't violently object to having some means of policing class
> or module privacy, but it does have consequences.  When it's a
> convention, you can break it; when it isn't, you can't, even if
> you do have good reason.  Add that to the obviousness of the
> "leading underscore => private" convention, and I just don't see
> a burning need for it, that's all.

Bare in mind also, that enfocing access control / policing as you
called it has a performance hit as the machine (the Python vm)
has to perform checks each time members of an object are accessed.

I can think of no reason to want to do this at runtime hwatosever
and I've been developing in Python for quite some years now.

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread r
> public = no leading underscore
> private = one leading underscore
> protected = two leading underscores
>
> Python uses encapsulation by convention rather than by enforcement.

Very well said Terry!

I like that python does not force me to do "everything" but does force
things like parenthesis in a function/method call whether or not an
argument is required/expected. This makes for very readable code.
Visual parsing a Python file is very easy on the eyes due to this fact
-- Thanks Guido! We do not need to add three new keywords when there
is an accepted Pythonic way to handle public/private/protected
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 1:18 PM, Russ P.  wrote:
> Yes, but the fact that you can approximate OO programming in a
> particular language does not make that language object oriented. You
> can approximate OO programming in C, but that does not mean that C is
> an OO language.

Wrong. Not having strict and enforced access control 9_NOT_ encapsulation)
(Please stop confusing the two) is not a strict requirements of the OO model.

Remember that it is a model and not a strict set of requirements that
programming
languages must implement.

In fact, Python borrows features from the Functional Paradigm. Does this
make it a Functional Language ? No. Why ? Because one of the clear
requirements of the Functional Paradigm is that functions cannot have
side affects.

> So I can claim that Python is not strictly object oriented until it
> gets encapsulation (in the sense of data hiding). That is simply a
> fact, and no amount of pleading or obfuscation will change it.

In fact this is true, C can be seen as an programming language
that has features of the OO model.

I think one of the things you guys are missing out
here is that there are really only two Paradigms
or Machines. Functional and Imperative. And guess
what ? As it turns out we can implement functional
machines that run on top of imperative ones!

> Should Python get true encapsulation? I don't know. Maybe
> encapsulation cannot be added without excessive overhead or without
> compromising other more important aspects and features of the
> language. But I do know that not having encapsulation is a limitation
> to the use of Python for good software engineering. I may be in the
> minority in the Python "community" on this one, but I am apparently in
> the majority in the OO programming "community."

Again, stop confusing terminology.

Should Python get strict and enforce access control
of object members ? No. Why ? I can think of several
reasons.

Give me one use-case where you strictly require
that members of an object be private and their
access enforced as such ?

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Rhodri James
On Wed, 14 Jan 2009 02:27:09 -, Paul Rubin  
<"http://phr.cx"@nospam.invalid> wrote:



But, if something is done by convention, then departing from the
convention is by definition unconventional.  If you do something
unconventional in a program, it could be on purpose for a reason, or
it could be by accident indicating a bug.


I wouldn't violently object to having some means of policing class
or module privacy, but it does have consequences.  When it's a
convention, you can break it; when it isn't, you can't, even if
you do have good reason.  Add that to the obviousness of the
"leading underscore => private" convention, and I just don't see
a burning need for it, that's all.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Russ P.
On Jan 13, 6:04 pm, "James Mills" 
wrote:
> On Wed, Jan 14, 2009 at 11:50 AM, Russ P.  wrote:
> > Here's the definition on the Wikipedia page for object oriented
> > programming (and it does *not* sound like Python classes):
>
> > Encapsulation conceals the functional details of a class from objects
> > that send messages to it. ... Encapsulation is achieved by specifying
> > which classes may use the members of an object. The result is that
> > each object exposes to any class a certain interface — those members
> > accessible to that class. The reason for encapsulation is to prevent
> > clients of an interface from depending on those parts of the
> > implementation that are likely to change in future, thereby allowing
> > those changes to be made more easily, that is, without changes to
> > clients. For example, an interface can ensure that puppies can only be
> > added to an object of the class Dog by code in that class. Members are
> > often specified as public, protected or private, determining whether
> > they are available to all classes, sub-classes or only the defining
> > class. Some languages go further: Java uses the default access
> > modifier to restrict access also to classes in the same package, C#
> > and VB.NET reserve some members to classes in the same assembly using
> > keywords internal (C#) or Friend (VB.NET), and Eiffel and C++ allow
> > one to specify which classes may access any member.
>
> You do realize this is a model and not
> strictly a requirement. Quite a few things
> in Python are done merely by convention.
>
> Don't get caught up.
>
> --JamesMills

Yes, but the fact that you can approximate OO programming in a
particular language does not make that language object oriented. You
can approximate OO programming in C, but that does not mean that C is
an OO language.

So I can claim that Python is not strictly object oriented until it
gets encapsulation (in the sense of data hiding). That is simply a
fact, and no amount of pleading or obfuscation will change it.

Should Python get true encapsulation? I don't know. Maybe
encapsulation cannot be added without excessive overhead or without
compromising other more important aspects and features of the
language. But I do know that not having encapsulation is a limitation
to the use of Python for good software engineering. I may be in the
minority in the Python "community" on this one, but I am apparently in
the majority in the OO programming "community."
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 12:57 PM, Terry Reedy  wrote:
> public = no leading underscore
> private = one leading underscore
> protected = two leading underscores
>
> Python uses encapsulation by convention rather than by enforcement.

As mentioned previously this is not encapsulation, but
access control. But yes correct, this is how we conventionally
define access control over members of an object. It's up to the
programmer correctly adhere to the interface(s).

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Terry Reedy

Russ P. wrote:

On Jan 13, 5:29 pm, alex23  wrote:

On Jan 14, 10:45 am, "Russ P."  wrote:


The Wikipedia entry for "object-oriented programming" also lists
encapsulation as a "fundamental concept."

The Wikipedia entry for "encapsulation" defines it as "the grouping
together of data and functionality".

That sounds like Python classes & modules to me.


Here's the definition on the Wikipedia page for object oriented
programming (and it does *not* sound like Python classes):

Encapsulation conceals the functional details of a class from objects
that send messages to it. ... Encapsulation is achieved by specifying
which classes may use the members of an object. The result is that
each object exposes to any class a certain interface — those members
accessible to that class. The reason for encapsulation is to prevent
clients of an interface from depending on those parts of the
implementation that are likely to change in future, thereby allowing
those changes to be made more easily, that is, without changes to
clients. For example, an interface can ensure that puppies can only be
added to an object of the class Dog by code in that class. Members are
often specified as public, protected or private, determining whether


public = no leading underscore
private = one leading underscore
protected = two leading underscores

Python uses encapsulation by convention rather than by enforcement.


they are available to all classes, sub-classes or only the defining
class. Some languages go further: Java uses the default access
modifier to restrict access also to classes in the same package, C#
and VB.NET reserve some members to classes in the same assembly using
keywords internal (C#) or Friend (VB.NET), and Eiffel and C++ allow
one to specify which classes may access any member.
--
http://mail.python.org/mailman/listinfo/python-list



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


Re: Standard IPC for Python?

2009-01-13 Thread Philip Semanchuk


On Jan 13, 2009, at 6:41 PM, Mel wrote:


Philip Semanchuk wrote:


I'm working on message queue support, but the Sys V IPC API is a
headache and takes longer to code against than the POSIX API.


I hadn't found it that bad.  I have a C extension I should perhaps  
clean up

and make public.


Have you compared the SysV objects to the POSIX objects? I'll give you  
two examples of how SysV is more trouble with which to work.


Example 1 ---
The SysV objects expose a ton of information that show up as Python  
attributes. For instance, a sysv_ipc.Semaphore object has 16  
attributes: key, id, value, undo, block, mode, uid, gid, cuid, cgid,  
last_pid, waiting_for_nonzero, waiting_for_zero and o_time. The first  
two and last eight are read-only, the middle six are read-write.


Contrast this to a posix_ipc.Semaphore object which has two read-only  
attributes: name and value.


All of those attributes on the SysV object add up to a lot of code.  
Furthermore, the SysV attributes have types of key_t, mode_t, uid_t,  
gid_t, pid_t, time_t, etc. I've spent the past few days researching  
these types and trying to find out whether they're signed or unsigned,  
guaranteed to fit in a long, etc. I also need to know what Python  
types are appropriate for representing these. For instance, anything  
that can exceed a C long can also exceed a Python int, and so I need  
to return a Python long object if the C value exceeds LONG_MAX.


When I returned to the sysv_ipc code a few days ago, my intention was  
to add message queue support to it, but instead I've gotten distracted  
chasing type-related bugs that won't show up until e.g. someone  
compiles the module on a 64-bit platform and tries to use a key that  
exceeds 0x, or compiles it on some weird 16-bit embedded  
processor that exposes another of my flawed type assumptions. The  
POSIX API is so much simpler that I spend much less time working on  
type-related drudgery.


Example 2 ---
SysV shared memory has to be attached and detached and accessed with  
the un-Pythonic read & write methods. I'd like to support buffer-type  
access (like slicing), but that's more code to be written. And there's  
another 16 attributes to expose.


POSIX shared memory OTOH is mmapped, and there's already a Python  
library for that. For posix_ipc.SharedMemory objects I had to write a  
constructor, an unlink() method, and code for three read-only  
attributes and I was done. Nice.



I invite you to look at my extension and compare:
http://semanchuk.com/philip/sysv_ipc/

Maybe your code can benefit from what I've done, or vice versa.


Good luck
Philip


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


Re: urllib2 - 403 that _should_ not occur.

2009-01-13 Thread ajaksu
On Jan 13, 1:33 am, Philip Semanchuk  wrote:
> I don't think I understand you clearly. Whether or not Google et al  
> whitelist the Python UA isn't a Python issue, is it?

Hi, sorry for taking so long to reply :)

I imagine it's something akin to Firefox's 'Report broken website':
evangelism.

IMHO, if the PSF *cough* Steve *cough*  or individual Python hackers
can contact key sites (as Wikipedia, groups.google, etc.) the issue
can be solved sooner.

Instead of waiting for each whitelist maintainer's to find out we have
a new UA, go out and tell them. A template for such requests could
help those inside e.g. Google to bring the issue to the attention of
the whitelist admins. The community has lots of connections that could
be useful to pass the message along, if only 'led by the nose' to
achieve that :)

Hence, the suggestion to raise a bug.

Regards,
Daniel
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 12:27 PM, Paul Rubin
<"http://phr.cx"@nospam.invalid> wrote:
> "James Mills"  writes:
>> You do realize this is a model and not strictly a requirement. Quite
>> a few things in Python are done merely by convention.
>> Don't get caught up.
>
> But, if something is done by convention, then departing from the
> convention is by definition unconventional.  If you do something
> unconventional in a program, it could be on purpose for a reason, or
> it could be by accident indicating a bug.
>
> I don't understand why some folks spew such violent rhetoric against
> the idea of augmenting Python with features to alert you automatically
> when you depart from the convention, so that you can check that the
> departure is actually what you wanted.  A lot of the time, I find, the
> departures are accidental and automated checks would save me
> considerable debugging.

Amen to that! Finally someone with some sense and
his/her head screwed on properly! :)

Kudos to your thoughtful post :)

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


Re: problem calling method

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 11:28 AM,   wrote:
> class MyFrame(wx.Frame):
>def __init__(self, *args, **kwds):

It might be helpful here if you called
the parent __init__. Like so:

class MyFrame(wx.Frame):
   def __init__(self, *args, **kwds):
  super(MyFrame, self).__init__(*args, **kwargs)

...

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Paul Rubin
"James Mills"  writes:
> You do realize this is a model and not strictly a requirement. Quite
> a few things in Python are done merely by convention.
> Don't get caught up.

But, if something is done by convention, then departing from the
convention is by definition unconventional.  If you do something
unconventional in a program, it could be on purpose for a reason, or
it could be by accident indicating a bug.  

I don't understand why some folks spew such violent rhetoric against
the idea of augmenting Python with features to alert you automatically
when you depart from the convention, so that you can check that the
departure is actually what you wanted.  A lot of the time, I find, the
departures are accidental and automated checks would save me
considerable debugging.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Programming friction

2009-01-13 Thread Jervis Whitley
On Wed, Jan 14, 2009 at 12:29 PM, killsto  wrote:

>
> force. So lets say I am slowing down at a rate of -2m/s^2, if I hit 1,
> the next number will be -1 and I shoot off in the other direction. How
> do I fix this an still have backwards movement?
> --
> http://mail.python.org/mailman/listinfo/python-list
>

try something like:

force = max(force, 0)

where force is the force applied to the object that you have calculated.

this should ensure that the force is bounded to 0 in the negative
direction.

I believe that in pygame you can use the clock module to help you with your
timing issues (see the docs), and
perhaps attempt to keep a regular frame rate.

Cheers,

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


Re: why cannot assign to function call

2009-01-13 Thread Aaron Brady
On Jan 13, 5:06 pm, Mark Wooding  wrote:
snip
> I'm going to move away from the formal semantics stuff and try a
> different tack.  Here's what I think is the defining property of
> pass-by-value (distilled from the formal approach I described earlier,
> but shorn of the symbolism):
>
>   The callee's parameters are /new variables/, initialized /as if by
>   assignment/ from the values of caller's argument expressions.

In other words, the same as assignment in that language.

snip
> Because its argument passing works the same way as its assignment.

That would be called pass-by-assignment.  But you've just postponed
explaining yourself.  Stop delegating and work.
--
http://mail.python.org/mailman/listinfo/python-list


Re: 'Import sys' succeeds in C++ embedded code, but module is not fully visible

2009-01-13 Thread Christian Heimes
Ivan Illarionov schrieb:
> Ben Sizer  wrote:
>> What am I doing wrong?
> 
> What are you trying to achieve?
> If you want to modify sys.path I suggest using Python/C API directly:
> (boilerplate removed)
> PyImport_ImportModule("sys")
> PyObject_GetAttrString(sysmod_pointer, "path")
> PyList_Insert(pathobj_pointer, 0, path_python_str)

The sys module has its own set of special functions like
PySys_GetObject. The following (untested) code should take care of error
checking and ref counting.

#include "Python.h"

PyObject*
addtosyspath(const char* addpath) {
PyObject *syspath=NULL, *path=NULL;
int result;

if ((syspath = PySys_GetObject("path")) == NULL)
return NULL;
if ((path = PyString_FromString(addpath) == NULL) {
Py_DECREF(syspath);
return NULL;
}
result = PyList_Insert(syspath, 0, path);
Py_DECREF(syspath);
Py_DECREF(path);
if (result != 0)
return NULL;
Py_RETURN_NONE;
}

Christian

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


Re: ctype problem

2009-01-13 Thread Mark Tolonen


"Aaron Brady"  wrote in message 
news:6197f37d-0ea0-4430-a466-2f36b2011...@v42g2000yqj.googlegroups.com...

On Jan 13, 10:22 am, Grimson  wrote:

hello out there,
I have a problem with c-types.
I made a c-library, which expects a pointer to a self defined structure.

let the funtion call myfunction(struct interface* iface)

and the struct:
struct interface
{
int a;
int b;
char *c;

}

the Python ctype port of this structur would be:

class INTERFACE(Structure):
_fields_ = [("a" c_int),
("b", c_int),
("c", c_char)]

in my python-struct a create a instance of INTERFACE

myiface = INTERFACE()
myiface.a = ctypes.c_int(80)
myiface.b = ctypes.c_int(22)
...
than I make a pointer onto it.
p_iface = ctypes.pointer(myiface)
and I tried it also with a reference
r_iface = ctypes.byref(myiface)

but neither myclib.myfunction(p_iface) nor myclib.myfunction(r_iface)
works properly. The function is been called but it reads only zeros (0)
for each parameter (member in the struct).

Where is my fault?


I believe you want ("c",c_char_p), although I don't get the same error as 
you describe when I use c_char.  Below is my working code (Python 2.6.1 and 
Visual Studio 2008):


 x.py 
from ctypes import *

class INTERFACE(Structure):
   _fields_ = [
   ('a',c_int),
('b',c_int),
('c',c_char)
]

x = CDLL('x.dll')
i = INTERFACE()
i.a = 1
i.b = 2
i.c = 'hello'
x.myfunction(byref(i))

 cl /LD /W4 x.c -> x.dll 
#include 

struct interface
{
   int a;
   int b;
   char* c;
};

__declspec(dllexport)
void myfunction(struct interface* iface)
{
   printf("%d %d %s\n",iface->a,iface->b,iface->c);
}

-Mark


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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 11:50 AM, Russ P.  wrote:
> Here's the definition on the Wikipedia page for object oriented
> programming (and it does *not* sound like Python classes):
>
> Encapsulation conceals the functional details of a class from objects
> that send messages to it. ... Encapsulation is achieved by specifying
> which classes may use the members of an object. The result is that
> each object exposes to any class a certain interface — those members
> accessible to that class. The reason for encapsulation is to prevent
> clients of an interface from depending on those parts of the
> implementation that are likely to change in future, thereby allowing
> those changes to be made more easily, that is, without changes to
> clients. For example, an interface can ensure that puppies can only be
> added to an object of the class Dog by code in that class. Members are
> often specified as public, protected or private, determining whether
> they are available to all classes, sub-classes or only the defining
> class. Some languages go further: Java uses the default access
> modifier to restrict access also to classes in the same package, C#
> and VB.NET reserve some members to classes in the same assembly using
> keywords internal (C#) or Friend (VB.NET), and Eiffel and C++ allow
> one to specify which classes may access any member.

You do realize this is a model and not
strictly a requirement. Quite a few things
in Python are done merely by convention.

Don't get caught up.

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


problem calling method

2009-01-13 Thread pieterprovoost
I'm trying to call a method within my wx frame, but that doesn't seem to work. 
What am I doing wrong?

class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
self.Bind(wx.EVT_BUTTON, self.test, self.testbutton)
...
def sendmail(self):
...
   def test(self, event):
self.sendmail()
event.Skip()

Clicking the test button returns:

Traceback (most recent call last):
  File "D:\python\bx\bxgui.py", line 120, in test
self.sendmail()
AttributeError: 'MyFrame' object has no attribute 'sendmail'

Thanks!

--
This message was sent on behalf of pieterprovo...@gmail.com at 
openSubscriber.com
http://www.opensubscriber.com/messages/python-list@python.org/topic.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: 'Import sys' succeeds in C++ embedded code, but module is not fully visible

2009-01-13 Thread Ivan Illarionov
Ben Sizer  wrote:
> What am I doing wrong?

What are you trying to achieve?
If you want to modify sys.path I suggest using Python/C API directly:
(boilerplate removed)
PyImport_ImportModule("sys")
PyObject_GetAttrString(sysmod_pointer, "path")
PyList_Insert(pathobj_pointer, 0, path_python_str)

--
Ivan


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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Russ P.
On Jan 13, 5:29 pm, alex23  wrote:
> On Jan 14, 10:45 am, "Russ P."  wrote:
>
> > The Wikipedia entry for "object-oriented programming" also lists
> > encapsulation as a "fundamental concept."
>
> The Wikipedia entry for "encapsulation" defines it as "the grouping
> together of data and functionality".
>
> That sounds like Python classes & modules to me.

Here's the definition on the Wikipedia page for object oriented
programming (and it does *not* sound like Python classes):

Encapsulation conceals the functional details of a class from objects
that send messages to it. ... Encapsulation is achieved by specifying
which classes may use the members of an object. The result is that
each object exposes to any class a certain interface — those members
accessible to that class. The reason for encapsulation is to prevent
clients of an interface from depending on those parts of the
implementation that are likely to change in future, thereby allowing
those changes to be made more easily, that is, without changes to
clients. For example, an interface can ensure that puppies can only be
added to an object of the class Dog by code in that class. Members are
often specified as public, protected or private, determining whether
they are available to all classes, sub-classes or only the defining
class. Some languages go further: Java uses the default access
modifier to restrict access also to classes in the same package, C#
and VB.NET reserve some members to classes in the same assembly using
keywords internal (C#) or Friend (VB.NET), and Eiffel and C++ allow
one to specify which classes may access any member.
--
http://mail.python.org/mailman/listinfo/python-list


Re: are there some special about '\x1a' symbol

2009-01-13 Thread Grant Edwards
On 2009-01-12, John Machin  wrote:

> I didn't think your question was stupid. Stupid was (a) CP/M recording
> file size as number of 128-byte sectors, forcing the use of an in-band
> EOF marker for text files (b) MS continuing to regard Ctrl-Z as an EOF
> decades after people stopped writing Ctrl-Z at the end of text files.

I believe that "feature" was inherited by CP/M from DEC OSes
(RSX-11 or RSTS-11). AFAICT, all of CP/M's file I/O API
(including the FCB) was lifted almost directly from DEC's
PDP-11 stuff, which probably copied it from PDP-8 stuff.

Perhaps in the early 60's somebody at DEC had a reason.  The
really interesting thing is that we're still suffering because
of it 40+ years later.

-- 
Grant Edwards   grante Yow! I want to read my new
  at   poem about pork brains and
   visi.comouter space ...
--
http://mail.python.org/mailman/listinfo/python-list


Re: New Python 3.0 string formatting - really necessary?

2009-01-13 Thread Arlo Belshee
For R, and others who haven't read the PEP or worked a lot with the
web, here are some really strong advantages of the new string
formatting over the old.

Note: I'm not saying that you have to use one or the other. I'm just
pointing out some of the things that the new format gives us - things
which allow the next generation of application simplification
(especially web apps).

When working on resource-oriented, generalized display applications
(eg, most any modern website), you commonly run into the problem of
wanting to display a bunch of different things in a bunch of different
ways - and on the web, display means "convert to a string for the
browser". However, the mapping is not a complete graph. Rather, there
are usually some rules. For example:

 * I want to show the same thing to different people in different
ways, depending on permissions.
 * Sometimes I want to show a thing as a full display, and sometimes
as a link to go get more. Usually, the template (context) knows how I
want to show something, but the thing knows how to show itself.

I can solve this using the new string formatting. In particular, by
using the "{0.property}", "{variable[index]}", and similar
substitutions (none of which can be done in the old syntax). As a
result, I end up with an entire website, of an arbitrary number of
pages, being supported with one, 5-line "generate the view" method.
There is 0 code per page.

Here are some of the simpler examples. First, there might be a link to
a user's page:

"{0.display_name}"

Wait...isn't that the same? Yup. There's the first widget: a link. Any
resource that knows its own name and URL (and that's all of them) can
be shown as a link. Similar widget extraction hugely reduces the other
combinations I have to support - eliminating a lot of redundancy, and
many LoC.

However, display_name doesn't show up the same for all users.
Administrators often get additional data (such as the username),
everywhere they see a user's name. Friends of a user see little
rollovers that tell them more about that user - such as a photo.
Fortunately, I defined my user class like:

class User:
  @property
  def display_name(self):
# viewer-dependent context stuff here.

And the new string formatting calls my arbitrary code, without anyone
having to think about it. But display_name doesn't need to know how to
display a name - it just needs to choose which style to use. I can
also extract that out to a template, and then have "{0.first}" for friends and "{0.first} {0.last}
({0.username})" for admins, and so on. My display_name code just needs
to choose which representation to use - it doesn't define that format.
It just returns one of several opaque string constants / widgets,
making refactoring trivial.

Similarly, I can use "{resource.full_display_for_viewer}" or
"{resource.link_display}" to tell the resource how I want it to
display itself.

Hm. Doesn't that make widget sets (a la ToscaWidgets / TuboGears) and
template languages (such as Cheetah / Kid / Mako) a little obsolete?
Well, sorta. After all when displaying my user class, I can do this
too: "{self.blog_entries.recent.as_ordered_list.using.link_display}".
Is that pathological? Probably (unless you have a functional
programming background or like domain-specific languages). Looping is,
after all, one of the things a real templating system gives you.
However, now you don't need to use it for common (and simple) things.

Eventually, you do run into stuff for which you want a full templating
language. And I use them. For example, they define the base page
layouts. The point, however, is that a lot of the lower-level things
can be done without using the templating language. And this reduces
the number of Mako templates you have lying around, while still
allowing great decomposability.

Most of these things could be done by having the object override
__format__(self). However, that jams my display code in with the rest
of my resource class. This way, I can have templates pull out what
they want from my resources. And I can compute the template to use and
the resources to use it on independently, then just pass it to my
displayer method.

These are capabilities that %s has no chance to every approach. The
ability to use new-style format strings reducees my LoC by a half-ton,
and they make what they leave behind a lot easier to read. Being
higher-level constructs, they allow me to eliminate redundancy, and
that's the real purpose of a programmer.
--
http://mail.python.org/mailman/listinfo/python-list


Re: executing multiple functions in background simultaneously

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 11:35 AM, MRAB  wrote:
> The disadvantage of threads in Python (CPython, actually) is that
> there's the GIL (Global Interpreter Lock), so you won't get any speed
> advantage if the threads are mostly processor-bound.

The OP didn't really say what this function
does :) *sigh*

@OP: You have (at least in 2.6+) threading and multiprocessing modules
at your disposal.

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


Re: executing multiple functions in background simultaneously

2009-01-13 Thread MRAB

James Mills wrote:
On Wed, Jan 14, 2009 at 11:02 AM, Catherine Moroney 
 wrote:

I would like to spawn off multiple instances of a function and run
them simultaneously and then wait until they all complete. 
Currently I'm doing this by calling them as sub-processes 
executable from the command-line.  Is there a way of accomplishing 
the same thing without having to make command-line executables of

the function call?


Try using the python standard threading module.

Create multiple instances of Thread with target=your_function 
Maintain a list of these new Thread instnaces Join (wait) on them.


pydoc threading.Thread


The disadvantage of threads in Python (CPython, actually) is that
there's the GIL (Global Interpreter Lock), so you won't get any speed
advantage if the threads are mostly processor-bound.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Programming friction

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 11:29 AM, killsto  wrote:
> I'm trying to implement a basic user controlled sliding box with
> pygame. I have everything worked out, except for two things.

Try the pygame mailing list :)

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread alex23
On Jan 14, 10:45 am, "Russ P."  wrote:
> The Wikipedia entry for "object-oriented programming" also lists
> encapsulation as a "fundamental concept."

The Wikipedia entry for "encapsulation" defines it as "the grouping
together of data and functionality".

That sounds like Python classes & modules to me.

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


Programming friction

2009-01-13 Thread killsto
I'm trying to implement a basic user controlled sliding box with
pygame. I have everything worked out, except for two things.

The acceleration is changed once a second (for meters/second) this
leads to very jumpy movement. I need to add a way to check how long it
takes the program to loop and multiply the acceleration by that much.
(I think)

After I move, the box slows down appropriately, but then the speed
passes 0 and the box shoots off the other way. The equation (in real
life) is mS (Coefficient of static friction)*Normal Force >= friction
force. So lets say I am slowing down at a rate of -2m/s^2, if I hit 1,
the next number will be -1 and I shoot off in the other direction. How
do I fix this an still have backwards movement?
--
http://mail.python.org/mailman/listinfo/python-list


Re: executing multiple functions in background simultaneously

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 11:02 AM, Catherine Moroney
 wrote:
> I would like to spawn off multiple instances of a function
> and run them simultaneously and then wait until they all complete.
> Currently I'm doing this by calling them as sub-processes
> executable from the command-line.  Is there a way of accomplishing
> the same thing without having to make command-line executables
> of the function call?

Try using the python standard threading module.

Create multiple instances of Thread with target=your_function
Maintain a list of these new Thread instnaces
Join (wait) on them.

pydoc threading.Thread

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


executing multiple functions in background simultaneously

2009-01-13 Thread Catherine Moroney

Hello everybody,

I know how to spawn a sub-process and then wait until it
completes.  I'm wondering if I can do the same thing with
a Python function.

I would like to spawn off multiple instances of a function
and run them simultaneously and then wait until they all complete.
Currently I'm doing this by calling them as sub-processes
executable from the command-line.  Is there a way of accomplishing
the same thing without having to make command-line executables
of the function call?

I'm primarily concerned about code readability and ease of
programming.  The code would look a lot prettier and be shorter
to boot if I could spawn off function calls rather than
subprocesses.

Thanks for any advice,

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Russ P.
On Jan 13, 3:07 pm, Carl Banks  wrote:

> I've seen no evidence that any Python project is moving even remotely
> toward data encapsulation.  That would be a drastic change.  Even if
> it were only a minor change in the implementation (and it would not
> be), it would be a major stroke in the Python community.  It would
> basically cause a wholescale power shift from the user to the
> implementor.  As a user it'd be like the difference between living in
> a free democracy and a fascist dictatorship.

I just googled "object oriented principles." The first site that came
up lists four princicples:

- Encapsulation
- Abstraction
- Inheritance
- Polymorphism

The Wikipedia entry for "object-oriented programming" also lists
encapsulation as a "fundamental concept."

The first line on the python.org site says:

"Python is a dynamic object-oriented programming language that can be
used for many kinds of software development."

How can that possibly be true if you see "no evidence that any Python
project is moving even remotely toward data encapsulation"?

Semantics aside, I fail to understand your hostility toward a
fundamental concept of object-oriented programming. The difference
between a free democracy and a "fascist dictatorship"? Give me a
break!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Standard IPC for Python?

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 3:40 AM, Laszlo Nagy  wrote:
> Can anyone tell me if select.select works under OS X?

Yes it does.

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


Re: Standard IPC for Python?

2009-01-13 Thread James Mills
On Wed, Jan 14, 2009 at 2:25 AM, Laszlo Nagy  wrote:
> The question is: what is the standard way to implement fast and portable IPC
> with Python? Are there tools in the standard lib that can do this?

Certainly not standard by any means, but I use
circuits (1). Two or more processes can communicate
via  Bridge by propagating events.

Example: http://trac.softcircuit.com.au/circuits/browser/examples/remotepy.py

cheers
James

1. http://trac.softcircuit.com.au/circuits/
--
http://mail.python.org/mailman/listinfo/python-list


Re: python3.0 MySQLdb

2009-01-13 Thread Daniel Fetchinson
 I need something to connect to a database, preferably mysql, that
 works in python3.0 please.
>>> And your question is?
>>>
>>>
>> Surely it's fairly obvious that the question is "does such a thing
>> exist, and if so where can I find it?".
>
> Interestingly enough, the question was slightly (but importantly)
> different, though: the question really was "Does anybody has a patch for
> MySQLdb?"; as my reference to the existing interface to PostgreSQL
> was not sufficient for the OP.

Exactly. One could think about 3-4 different potentially useful
answers to the OP but when one sees 3-4 immediately right after
reading the post then probably there are a couple more still after
some thinking. So if the OP specifies exactly what he/she wants,
he/she will get more signal than noise.

Cheers,
Daniel


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Re: Extracting real-domain-name (without sub-domains) from a given URL

2009-01-13 Thread Terry Reedy

S.Selvam Siva wrote:


I doubt anyone's created a general ready-made solution for this, you'd
have to code it yourself.
To handle the common case, you can cheat and just .split() at the
periods and then slice and rejoin the list of domain parts, ex:
'.'.join(domain.split('.')[-2:])

Cheers,
Chris



Thank you Chris Rebert,
  Actually i tried with domain specific logic.Having 200 TLD like
.com,co.in,co.uk and tried to extract the domain name.
  But my boss want more reliable solution than this method,any way i
will try to find some alternative solution.


I make a dict mapping TLDs to number of parts to strip off
parts = {
'com':1,
'in':2,
'org':1,
'uk':2,
}
etc

If certain TLDs need a special function, define the function first and 
map that TLD to the function and then switch on the type of value (int 
or function) when you look it up.


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


Re: Python 3.0 urllib.parse.parse_qs results in TypeError

2009-01-13 Thread John Machin
On Jan 14, 9:56 am, Andy Grove  wrote:
> On Jan 13, 3:08 pm, John Machin  wrote:
>
> > Please show the full traceback.
>
> John,
>
> Thanks. Here it is:
>
>   File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
> python3.0/socketserver.py", line 281, in _handle_request_noblock
>     self.process_request(request, client_address)
>   File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
> python3.0/socketserver.py", line 307, in process_request
>     self.finish_request(request, client_address)
>   File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
> python3.0/socketserver.py", line 320, in finish_request
>     self.RequestHandlerClass(request, client_address, self)
>   File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
> python3.0/socketserver.py", line 614, in __init__
>     self.handle()
>   File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
> python3.0/http/server.py", line 363, in handle
>     self.handle_one_request()
>   File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
> python3.0/http/server.py", line 357, in handle_one_request
>     method()
>   File "/Users/andy/Development/EclipseWorkspace/dbsManage/kernel.py",
> line 178, in do_POST
>     form = urllib.parse.parse_qs(qs, keep_blank_values=1)
>   File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
> python3.0/urllib/parse.py", line 351, in parse_qs
> 
>     for name, value in parse_qsl(qs, keep_blank_values,
> strict_parsing):
>   File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
> python3.0/urllib/parse.py", line 377, in parse_qsl
>     pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
> TypeError: Type str doesn't support the buffer API


| Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit
(Intel)] on win32
| Type "help", "copyright", "credits" or "license" for more
information.
| >>> qs_bytes = b'a;b&c;d'
| >>> qs_str = 'a;b&c;d'
| >>> pairs = [s2 for s1 in qs_bytes.split('&') for s2 in s1.split
(';')]
| Traceback (most recent call last):
|   File "", line 1, in 
| TypeError: Type str doesn't support the buffer API
| >>> pairs = [s2 for s1 in qs_str.split('&') for s2 in s1.split(';')]
| >>> pairs
| ['a', 'b', 'c', 'd']
| >>> b'x&y'.split('&')
| Traceback (most recent call last):
|   File "", line 1, in 
| TypeError: Type str doesn't support the buffer API
| >>> b'x&y'.split(b'&')
| [b'x', b'y']
| >>> 'x&y'.split('&')
| ['x', 'y']
| >>>

The immediate cause is that as expected mixing str and bytes raises an
exception -- this one however qualifies as "not very informative" and
possibly wrong [not having inspected the code for whatever.split() I'm
left wondering what is the relevance of the buffer API].

The docs for urllib.parse.parse_qs() and .parse_qsl() are a bit vague:
"""query string given as a string argument (data of type application/x-
www-form-urlencoded)""" ... does "string" mean "str only" or "str or
bytes"?

Until someone can give an authoritative answer [*], you might like to
try decoding your data (presuming you know what it is or how to dig it
out like you found the type and length) and feeding the result to
the .parse_qs().

[*] I know next to zilch about cgi and urllib -- I'm just trying to
give you some clues to see if you can get yourself back on the road.

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


Re: [OT] Re: are there some special about '\x1a' symbol

2009-01-13 Thread Terry Reedy

Gabriel Genellina wrote:
En Mon, 12 Jan 2009 12:00:16 -0200, John Machin  
escribió:



I didn't think your question was stupid. Stupid was (a) CP/M recording
file size as number of 128-byte sectors, forcing the use of an in-band
EOF marker for text files (b) MS continuing to regard Ctrl-Z as an EOF
decades after people stopped writing Ctrl-Z at the end of text files.


This is called "backwards compatibility" and it's a good thing :)


But it does not have to be the default or only behavior to be available.

Consider the Atucha II nuclear plant, started in 1980, based on a design 
from 1965, and still unfinished. People require access to the complete 
design, plans, specifications, CAD drawings... decades after they were 
initially written.
I actually do use (and maintain! -- ugh!) some DOS programs. Some people 
would have a hard time if they could not read their old data with new 
programs.
Even Python has a "print" statement decades after nobody uses a teletype 
terminal anymore...




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


Re: Could you suggest optimisations ?

2009-01-13 Thread Terry Reedy

Barak, Ron wrote:

Hi,

In the attached script, the longest time is spent in the following 
functions (verified by psyco log):


I cannot help but wonder why and if you really need all the rigamorole 
with file pointers, offsets, and tells instead of


for line in open(...):
  do your processing.




def match_generator(self,regex):
"""
Generate the next line of self.input_file that
matches regex.
"""
generator_ = self.line_generator()
while True:
self.file_pointer = self.input_file.tell()
if self.file_pointer != 0:
self.file_pointer -= 1
if (self.file_pointer + 2) >= self.last_line_offset:
break
line_ = generator_.next()
print "%.2f%%   \r" % (((self.last_line_offset - 
self.input_file.tell()) / (self.last_line_offset * 1.0)) * 100.0),

if not line_:
break
else:
match_ = regex.match(line_)
groups_ = re.findall(regex,line_)
if match_:
yield line_.strip("\n"), groups_
 
def get_matching_records_by_regex_extremes(self,regex_array):

"""
Function will:
Find the record matching the first item of regex_array.
Will save all records until the last item of regex_array.
Will save the last line.
Will remember the position of the beginning of the next line in
self.input_file.
"""
start_regex = regex_array[0]
end_regex = regex_array[len(regex_array) - 1]
 
all_recs = []

generator_ = self.match_generator
 
try:

match_start,groups_ = generator_(start_regex).next()
except StopIteration:
return(None)
 
if match_start != None:

all_recs.append([match_start,groups_])
 
line_ = self.line_generator().next()

while line_:
match_ = end_regex.match(line_)
groups_ = re.findall(end_regex,line_)
if match_ != None:
all_recs.append([line_,groups_])
return(all_recs)
else:
all_recs.append([line_,[]])
line_ = self.line_generator().next()
 
def line_generator(self):

"""
Generate the next line of self.input_file, and update
self.file_pointer to the beginning of that line.
"""
while self.input_file.tell() <= self.last_line_offset:
self.file_pointer = self.input_file.tell()
line_ = self.input_file.readline()
if not line_:
break
yield line_.strip("\n")

I was trying to think of optimisations, so I could cut down on 
processing time, but got no inspiration.

(I need the "print "%.2f%%   \r" ..." line for user's feedback).

Could you suggest any optimisations ?
Thanks,
Ron.
 
 
P.S.: Examples of processing times are:


* 2m42.782s  on two files with combined size of792544 bytes
  (no matches found).
* 28m39.497s on two files with combined size of 4139320 bytes
  (783 matches found). 


These times are quite unacceptable, as a normal input to the program
would be ten files with combined size of ~17MB.




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


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


Re: Standard IPC for Python?

2009-01-13 Thread Terry Reedy

Laszlo Nagy wrote:




I was suggesting getting posix_ipc or sysv_ipc to compile against a 
compatibility library (Cygwin?) under Windows. It sounds like you're 
proposing something totally different, no?
OK I see. But probably I do not want to use Cygwin because that would 
create another dependency. I understand that posix_ipc/sysv is not 
natively supported under windows. What about this:




A few comments: First, the issue of cross-platform IPC, and its 
difficulties, has come up occasionally, but most with the knowledge of 
writing stuff for one system (esp. Windows) tend to stick with that system.



- create a wrapper, using ctypes, /windll / cdll/ to access API functions


ctypes was only added in 2.5.  It should make some things easier than 
they would have been before.


- use CreateFileMapping on the page file to create shared memory (a la 
windows: http://msdn.microsoft.com/en-us/library/aa366537.aspx)
- use CreateEvent/WaitForSingleObject for signaling 
(http://msdn.microsoft.com/en-us/library/ms682396(VS.85).aspx)
- these should be enough to implement shared memory functions and 
message queues under windows, and that might be a quick solution at 
least for me.
- it might also be used to emulate the same posix_ipc interface, without 
any external dependency added (cygwin).


That would be good.



All I care about is to create a working message queue. But if you think 
that this ctypes hack would be useful for other users, then I can try to 
implement it.


I must tell you that I'm not very familiar with C programming (it was a 
long time ago...) and I do not own MSVC.


Python compiles, I believe, with the free VCExpress.  But I would start 
with ctypes.


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


Re: Standard IPC for Python?

2009-01-13 Thread Mel
Philip Semanchuk wrote:

> I'm working on message queue support, but the Sys V IPC API is a
> headache and takes longer to code against than the POSIX API.

I hadn't found it that bad.  I have a C extension I should perhaps clean up
and make public.

Mel.

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


cgi.FieldStorage hanging with Python 3.0 (but works with 2.5.1)

2009-01-13 Thread Andy Grove
I'm trying to get a Python web server running that I can upload files
to. I actually have the code running with the version of Python pre-
installed on Mac OS X but it doesn't work with ActivePython 3.0 - I
have not been able to compile Python from source myself to see if the
issue is specific to the ActivePython distribution.

Here is the relevant code:

class MyHandler(http.server.BaseHTTPRequestHandler):
  def do_POST(self):
try:
print( "Calling cgi.FieldStorage()" )
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
 'CONTENT_TYPE':self.headers['Content-
Type'],
 })
print( "Calling cgi.FieldStorage()" )

The client is the following HTML form being submitted with Firefox
3.0.5 running on the same machine. The browser also hangs, waiting for
a response from the server.

http://localhost:8090/deploy"; method="POST"
enctype="multipart/form-data">

File:
 



As I said, this all works fine with Python 2.5.1 pre-installed.

Any suggestions?

Thanks,

Andy.

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


Re: why cannot assign to function call

2009-01-13 Thread Mark Wooding
Steven D'Aprano  wrote:

> I found it interesting. 

Well, that's something, at any rate.

> I think this conversation is reaching it's natural end. Frustration
> levels are rising. 

I think you may be right.  That said...

> So I'm going to take a different tack in an attempt to reduce
> frustration levels: if I can't convince the other side they're wrong,
> can I at least get them to understand where I'm coming from a little
> better?

Maybe...

> As I see it, this conversation is floundering on two radically different 
> ideas about what it means to say a language uses pass-by-foo.

You might be right, but I'm unconvinced.

> On the one hand, some people (me and possibly rurpy) consider "this is 
> pass-by-foo" to be a statement about behaviour directly visible to the 
> programmer. We have a set of behavioral traits in mind, and if a language 
> exhibits those behaviours, then it is clearly and obviously pass-by-foo 
> no matter how that behaviour is implemented. I'll call these the 
> behaviorists.

Here's the problem.  I think I'm in that camp too!

I'm going to move away from the formal semantics stuff and try a
different tack.  Here's what I think is the defining property of
pass-by-value (distilled from the formal approach I described earlier,
but shorn of the symbolism):

  The callee's parameters are /new variables/, initialized /as if by
  assignment/ from the values of caller's argument expressions.

I'd just like to examine that for a bit.  Firstly, let's expand it from
the soundbite: basically what it says is that you should be able to
replace

  function mumble(a, b, c) { stuff in terms of a, b, and c }
  ...
  mumble(1 + 2, xyz, whatever)

with

  ...
  fresh_a = 1 + 2
  fresh_b = xyz
  fresh_c = whatever
  stuff in terms of fresh_a, fresh_b, and fresh_c

with no observable difference (here, fresh_a and so on are a variable
names not appearing in the rest of the program).  So:

  * It captures C's behaviour (at least if you don't count arrays --
let's not open that one again), and Pascal's normal behaviour.
Assigning to the parameters doesn't affect the caller's argument
variables because the parameters are fresh variables.

  * It /doesn't/ capture Fortran's behaviour, or Pascal's `var'
parameters, because obviously assignment to parameters in Fortran
/can/ affect the caller's argument variables

  * It also doesn't capture exotic things like Algol's call by name, and
lazy evaluation, because there's an evaluation step in there.

My soundbite definition for pass-by-reference is this:

  The callee's parameters are merely /new names/ for the caller's
  argument variables -- as far as that makes sense.

There's a caveat there for argument expressions which don't correspond
directly to variables -- and I've glossed over the issue of lvalue
expressions which designate locations and all of that.  The idea is that
you can replace

  function mumble(a, b) { stuff in terms of a and b }
  ...
  mumble(xyz, whatever)

by

  ...
  stuff in terms of xyz and whatever

This does indeed capture Fortran, and Pascal's `var', while excluding C
and Pascal non-`var'.  Good!

So... obviously I'm going to claim that Python is pass-by-value.  Why?
Because its argument passing works the same way as its assignment.

But! (you claim) ...

> Python simply can't be pass-by-value, because it doesn't behave like
> pass-by-value in other languages (particularly C and Pascal).

Ah! (say I) but assignment in C and Pascal looks different from the way
it looks in C -- and in exactly the same way that argument passing looks
different.  And there, I think, I'm going to rest my case.

I'm sorry I took so long to distill these thoughts.  Thank you for
putting up with my theoretical meanderings on the way.

-- [mdw]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 urllib.parse.parse_qs results in TypeError

2009-01-13 Thread Andy Grove
I don't fully understand this but if I pass in "str(qs)" instead of
"qs" then the call works. However, qs is returned from file.read()
operation so shouldn't that be a string already?

In case it's not already obvious, I am new to Python :-) .. so I'm
probably missing something here.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Carl Banks
On Jan 13, 4:03 pm, Paul Rubin  wrote:
> Bruno Desthuilliers  writes:
> > And that's the problem : what Paul suggests are not "improvements" but
> > radical design changes.
>
> Eh?  I think of them as moderate and incremental improvements, in a
> direction that Python is already moving in.

I've seen no evidence that any Python project is moving even remotely
toward data encapsulation.  That would be a drastic change.  Even if
it were only a minor change in the implementation (and it would not
be), it would be a major stroke in the Python community.  It would
basically cause a wholescale power shift from the user to the
implementor.  As a user it'd be like the difference between living in
a free democracy and a fascist dictatorship.


>  Radical would be
> something like a full-scale static type system.
>
> > I really wonder why peoples that seems to dislike one of the central
> > features of Python - it's dynamism - still use it (assuming of
> > course they are free to choose another language).
>
> I certainly don't think dynamism is central to Python. In what I see
> as well-developed Python programming style, it's something that is
> only rarely used in any important way.

You're in the minority, then.


> I'd spend much less time
> debugging if I got compiler warnings whenever I used dynamism without
> a suitable annotation.  The 1% of the time where I really want to use
> dynamism I don't see any problem with putting in an appropriate
> decorator, superclass, or whatever.

Well, I guess you are the sacrifical lamb so that everyone else can
take advantage of the dynamicism.


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


'Import sys' succeeds in C++ embedded code, but module is not fully visible

2009-01-13 Thread Ben Sizer
I have the following C++ code and am attempting to embed Python 2.5,
but although the "import sys" statement works, attempting to reference
"sys.path" from inside a function after that point fails. It's as if
it's not treating it as a normal module but as any other global
variable which I'd have to explicitly qualify.


Py_InitializeEx(0); // the zero skips registration of signal
handlers.
PyObject* ourNamespace_ = PyDict_New();
PyDict_SetItemString(ourNamespace_, "__builtins__",
PyEval_GetBuiltins());
PyObject* locals = PyDict_New();

const char* scriptStr =
"print '1'\n"
"import sys\n"
"print sys.path\n"
"def debug_path_info():\n"
"print 'These are the directories Python looks into for
modules and source files:'\n"
"print '2'\n"
"for folder in sys.path:\n"
"print folder\n"
"print '--'\n"
"print 'This would be your present working folder/
directory:'\n"
"print '3'\n"
"print sys.path[0]\n"
"debug_path_info()\n";

PyObject* scriptResult = PyRun_String(
scriptStr,  // Python code to execute
Py_file_input,
ourNamespace_,   // globals dictionary
locals);// locals dictionary

if (!scriptResult)
{
std::cerr << "Python error: " << "Unhandled Python exception 
from
script." << std::endl;
PyErr_Print();
}
else
{
Py_DECREF(scriptResult); // don't need result any more
}

Py_DECREF(locals);
Py_DECREF(ourNamespace_);
Py_Finalize();


And the output is like this:

1
['E:\\code\\Python25\\lib\\site-packages\\turbokid-1.0.4-py2.5.egg',
'E:\\code\\
Python25\\lib\\site-packages\\turbocheetah-1.0-py2.5.egg', 'E:\\code\
\Python25\\
lib\\site-packages\\simplejson-1.8.1-py2.5-win32.egg', 'E:\\code\
\Python25\\lib\
\site-packages\\ruledispatch-0.5a0.dev_r2306-py2.5-win32.egg', 'E:\
\code\\Python
25\\lib\\site-packages\\pastescript-1.6.2-py2.5.egg', 'E:\\code\
\Python25\\lib\\
site-packages\\formencode-1.0.1-py2.5.egg', 'E:\\code\\Python25\\lib\
\site-packa
ges\\decoratortools-1.7-py2.5.egg', 'E:\\code\\Python25\\lib\\site-
packages\\con
figobj-4.5.2-py2.5.egg', 'E:\\code\\Python25\\lib\\site-packages\
\cherrypy-2.3.0
-py2.5.egg', 'E:\\code\\Python25\\lib\\site-packages\\kid-0.9.6-
py2.5.egg', 'E:\
\code\\Python25\\lib\\site-packages\\cheetah-2.0.1-py2.5-win32.egg',
'E:\\code\\
Python25\\lib\\site-packages\\pyprotocols-1.0a0-py2.5-win32.egg', 'E:\
\code\\Pyt
hon25\\lib\\site-packages\\pastedeploy-1.3.1-py2.5.egg', 'E:\\code\
\Python25\\li
b\\site-packages\\paste-1.6-py2.5.egg', 'E:\\code\\Python25\\lib\\site-
packages\
\sqlobject-0.10.0-py2.5.egg', 'E:\\code\\Python25\\lib\\site-packages\
\tgfastdat
a-0.9a7-py2.5.egg', 'E:\\code\\Python25\\lib\\site-packages\
\webhelpers-0.6-py2.
5.egg', 'E:\\code\\Python25\\lib\\site-packages\\shove-0.1.3-
py2.5.egg', 'E:\\co
de\\Python25\\lib\\site-packages\\boto-1.3a-py2.5.egg', 'E:\\code\
\Python25\\lib
\\site-packages\\sqlalchemy-0.5.0beta3-py2.5.egg', 'E:\\code\\Python25\
\lib\\sit
e-packages\\turbojson-1.1.4-py2.5.egg', 'E:\\code\\Python25\\lib\\site-
packages\
\setuptools-0.6c9-py2.5.egg', 'E:\\code\\Python25\\lib\\site-packages\
\turbogear
s-1.0.8-py2.5.egg', 'C:\\WINDOWS\\system32\\python25_d.zip', 'E:\\code\
\Python25
\\Lib', 'E:\\code\\Python25\\DLLs', 'E:\\code\\Python25\\Lib\\lib-tk',
'e:\\Visu
al Studio 2008\\Projects\\StacklessEmbed\\StacklessEmbed', 'e:\\Visual
Studio 20
08\\Projects\\StacklessEmbed\\Debug', 'E:\\code\\Python25', 'E:\\code\
\Python25\
\lib\\site-packages', 'E:\\code\\Python25\\lib\\site-packages\\PIL',
'E:\\code\\
Python25\\lib\\site-packages\\wx-2.8-msw-unicode']
These are the directories Python looks into for modules and source
files:
2
Python error: Unhandled Python exception from script.
Traceback (most recent call last):
  File "", line 13, in 
  File "", line 7, in debug_path_info
NameError: global name 'sys' is not defined
[12532 refs]


(Incidentally, the Stackless references are because I was originally
trying to embed Stackless, but I reverted to vanilla 2.5 to see if it
was a Stackless specific issue, which it appears not.)

Another interesting thing is that sys.path[0] doesn't appear to be the
current working directory, despite several sources online suggesting
it should be.

What am I doing wrong?

--
Ben Sizer












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


Re: python3.0 MySQLdb

2009-01-13 Thread Martin v. Löwis
Steve Holden wrote:
> Daniel Fetchinson wrote:
>>> I need something to connect to a database, preferably mysql, that
>>> works in python3.0 please.
>> And your question is?
>>
>>
> Surely it's fairly obvious that the question is "does such a thing
> exist, and if so where can I find it?". 

Interestingly enough, the question was slightly (but importantly)
different, though: the question really was "Does anybody has a patch for
MySQLdb?"; as my reference to the existing interface to PostgreSQL
was not sufficient for the OP.

Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 urllib.parse.parse_qs results in TypeError

2009-01-13 Thread Andy Grove
On Jan 13, 3:08 pm, John Machin  wrote:

> Please show the full traceback.

John,

Thanks. Here it is:

  File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
python3.0/socketserver.py", line 281, in _handle_request_noblock
self.process_request(request, client_address)
  File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
python3.0/socketserver.py", line 307, in process_request
self.finish_request(request, client_address)
  File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
python3.0/socketserver.py", line 320, in finish_request
self.RequestHandlerClass(request, client_address, self)
  File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
python3.0/socketserver.py", line 614, in __init__
self.handle()
  File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
python3.0/http/server.py", line 363, in handle
self.handle_one_request()
  File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
python3.0/http/server.py", line 357, in handle_one_request
method()
  File "/Users/andy/Development/EclipseWorkspace/dbsManage/kernel.py",
line 178, in do_POST
form = urllib.parse.parse_qs(qs, keep_blank_values=1)
  File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
python3.0/urllib/parse.py", line 351, in parse_qs

for name, value in parse_qsl(qs, keep_blank_values,
strict_parsing):
  File "/Library/Frameworks/Python.framework/Versions/3.0/lib/
python3.0/urllib/parse.py", line 377, in parse_qsl
pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
TypeError: Type str doesn't support the buffer API
--
http://mail.python.org/mailman/listinfo/python-list


Weird behaviour re: Python on Windows

2009-01-13 Thread Kevin Jing Qiu
I've been experiencing weird behavior of Python's os module on Windows:

Here's the environment:
Box1: Running Windows 2003 Server with Apache+mod_python
Box2: Running Windows 2003 Server with Zope/Plone and Z:\ mapped to D:\
on Box1

It appears any os calls that deals with file/dir on the mapped drive is
problematic. More specifically, os.stat(path), os.path.exists(path)
gives 'File not found' when path is on the mapped drive. Wait, this gets
better: when I'm in the debug mode (or Python interactive shell),
everything works fine! Os.stat, os.path.exists, os.fstat, etc, worked as
expected. I tried PyWin32 extension's GetFileSize() method and the same
thing happens: debug or interactive mode works fine, but when Plone is
run in non-debug mode, the problems begin.

I swear this isn't a Plone problem either. I switched the configuration.
Now Box1 has a network drive mapped to Box2's D:\. The custom Apache
filter we have (which is written in python executed by mod_python)
complains that it can't find the file which is on the mapped drive.

So there you go. I'm wondering if anyone else experienced such problem.
Any suggestions or input is appreciated!

Thanks,

Kevin

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


Re: Scheduled Tasks - SetFlags

2009-01-13 Thread Roger Upole

kj7ny wrote:
> How do I enable/disable a scheduled task using Python?
>
> I can get to a task:
>
>self.ts=pythoncom.CoCreateInstance
> (taskscheduler.CLSID_CTaskScheduler,None,pythoncom.CLSCTX_INPROC_SERVER,taskscheduler.IID_ITaskScheduler)
>self.ts.SetTargetComputer(u'SomeServer')
>self.tasks=self.ts.Enum()
>for task in self.tasks:
>self.t=self.ts.Activate(task)
>if self.t.GetAccountInformation().lower().find('SomeUser')
>>=0:
>print self.t.GetFlags()
>
> I can find if a task is enabled or not and toggle it:
>
>disabled=self.t.GetFlags() &
> taskscheduler.TASK_FLAG_DISABLED == taskscheduler.TASK_FLAG_DISABLED
>print 'Originally Disabled: %s'%(disabled,)
>if disabled:
>self.t.SetFlags(self.t.GetFlags() &
> ~taskscheduler.TASK_FLAG_DISABLED)
>else:
>self.t.SetFlags(self.t.GetFlags() |
> taskscheduler.TASK_FLAG_DISABLED)
>disabled=self.t.GetFlags() &
> taskscheduler.TASK_FLAG_DISABLED == taskscheduler.TASK_FLAG_DISABLED
>print 'Recheck Disabled: %s'%(disabled,)
>
> ... "Recheck Disabled" shows that the value "says" it has been
> disabled.
>
> The problem is that if I run it again and again, "Originally Disabled"
> is always the same.  In other words, "Recheck Disabled" does NOT
> stick.  It's like I'm missing a .commit()
>

Your missing commit is spelled

pf=t.QueryInterface(pythoncom.IID_IPersistFile)
pf.Save(None,1)

   Roger




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


Pydev 1.4.2 Released

2009-01-13 Thread Fabio Zadrozny
Hi All,

Pydev and Pydev Extensions 1.4.2 have been released

Details on Pydev Extensions: http://www.fabioz.com/pydev
Details on Pydev: http://pydev.sf.net
Details on its development: http://pydev.blogspot.com

Release Highlights in Pydev Extensions:
-

* Context insensitive code-completion working with multiple interpreters
* Fixed code analysis problem on staticmethod
* Giving proper warning on version mismatch
* Remote debugger fix


Release Highlights in Pydev:
--

* Interpreter can be configured on a per-project basis
* Jython 2.5b0 properly supported
* Find definition working for Jython builtins
* Run: can be python/jython even if it doesn't match the interpreter
configured for the project
* Fixed problem on find definition if one of the interpreters was not configured
* Fixed halting condition that could occur on code-completion
* __file__ available in code-completion
* Reorganized preferences (removed editor preferences from the root)
* Preferences for showing hover info
* Fixed problem when formatting binary operator that was in a new line
* When converting spaces to tabs (and vice-versa), the number of
spaces for each tab is asked
* Debugger
  o When finishing the user code debugging, it doesn't step into
the debugger code anymore
  o Fixes for working with Jython
  o Fix for Python 3.0 integration (could not resolve variables)



What is PyDev?
---

PyDev is a plugin that enables users to use Eclipse for Python and
Jython development -- making Eclipse a first class Python IDE -- It
comes with many goodies such as code completion, syntax highlighting,
syntax analysis, refactor, debug and many others.


Cheers,

-- 
Fabio Zadrozny
--
Software Developer

Aptana
http://aptana.com/python

Pydev Extensions
http://www.fabioz.com/pydev

Pydev - Python Development Enviroment for Eclipse
http://pydev.sf.net
http://pydev.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 urllib.parse.parse_qs results in TypeError

2009-01-13 Thread John Machin
On Jan 14, 6:54 am, ag73  wrote:
> Hi,
>
> I am trying to parse data posted to a Python class that extends
> http.server.BaseHTTPRequestHandler. Here is the code I am using:
>
>         def do_POST(self):
>                 ctype, pdict = cgi.parse_header(self.headers['Content-Type'])
>                 length = int(self.headers['Content-Length'])
>                 if ctype == 'application/x-www-form-urlencoded':
>                         qs = self.rfile.read(length)
>                         print("qs="+str(qs))
>                         form = urllib.parse.parse_qs(qs, keep_blank_values=1)
>
> The print statement shows the following output, so it looks like the
> data is being posted correctly:
>
> qs=b'file_data=b
> %27IyEvdXNyL2Jpbi9lbnYgcHl0aG9uCiMgZW5jb2Rpbmc6IHV0Zi04CiIiIgp1bnRpdGxlZC5w­eQoK
> %5CnQ3JlYXRlZCBieSBBbmR5IEdyb3ZlIG9uIDIwMDgtMTItMDIuCkNvcHlyaWdodCAoYykgMjA­wOCBf
> %5CnX015Q29tcGFueU5hbWVfXy4gQWxsIHJpZ2h0cyByZXNlcnZlZC4KIiIiCgppbXBvcnQgc3l­zCmlt
> %5CncG9ydCBvcwoKCmRlZiBtYWluKCk6CglwcmludCAibmFtZTE9dmFsdWUxIgoJcHJpbnQgIm5­hbWUy
> %5CnPXZhbHVlMiIKCgppZiBfX25hbWVfXyA9PSAnX19tYWluX18nOgoJbWFpbigpCgo%3D
> %5Cn%27&filename=test.py'
>
> However, the last line of code that calls parse_qs causes the
> following exception to be thrown:
>
> 
> Type str doesn't support the buffer API

Please show the full traceback.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Standard IPC for Python?

2009-01-13 Thread Philip Semanchuk


On Jan 13, 2009, at 4:31 PM, drobi...@gmail.com wrote:


On Jan 13, 2:37 pm, Philip Semanchuk  wrote:

I was suggesting getting posix_ipc or sysv_ipc to compile against a
compatibility library (Cygwin?) under Windows. It sounds like you're
proposing something totally different, no?


It's not really correct to call Cygwin a compatibility library. It's
more of a separate system.


Thanks for the education; I'm obviously not very familiar with it.


In any case, the current version (1.5.25) does not support sem_unlink
or shm_unlink so posix_ipc does not build. Cygwin 1.7, currently under
test, will support these.  I haven't tried it yet. I expect it will
work OOTB.


Thanks for the report. Strange that it supports the functions to open  
but not close semaphores. IN any case, I'd be very happy if posix_ipc  
or sysv_ipc would work with few or no modifications under Cygwin.



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


Re: Standard IPC for Python?

2009-01-13 Thread Philip Semanchuk


On Jan 13, 2009, at 3:04 PM, Laszlo Nagy wrote:





I was suggesting getting posix_ipc or sysv_ipc to compile against a  
compatibility library (Cygwin?) under Windows. It sounds like  
you're proposing something totally different, no?
OK I see. But probably I do not want to use Cygwin because that  
would create another dependency. I understand that posix_ipc/sysv is  
not natively supported under windows. What about this:


- create a wrapper, using ctypes, /windll / cdll/ to access API  
functions
- use CreateFileMapping on the page file to create shared memory (a  
la windows: http://msdn.microsoft.com/en-us/library/aa366537.aspx)
- use CreateEvent/WaitForSingleObject for signaling (http://msdn.microsoft.com/en-us/library/ms682396(VS.85).aspx 
)
- these should be enough to implement shared memory functions and  
message queues under windows, and that might be a quick solution at  
least for me.


Python has the mmap module which might work a lot like shared memory.  
I'm not clear on the differences, honestly.


Named pipes might be a cleaner way to implement message queues:
http://msdn.microsoft.com/en-us/library/aa365590(VS.85).aspx


- it might also be used to emulate the same posix_ipc interface,  
without any external dependency added (cygwin).


It'd be nice to have message queues/named pipes working under Windows.

If I were you, I'd steer clear of calling them something specific like  
"SysV" or "POSIX" messages queues. That will create an expectation of  
certain semantics, and you might find it difficult to fulfill that  
promise in certain cases (e.g. implementing the POSIX function  
mq_notify() ). If you call them Nagy message queues then no one will  
be disappointed or surprised as long as your code implements FIFO IPC.



Bye
Philip


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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Paul Rubin
Bruno Desthuilliers  writes:
> And that's the problem : what Paul suggests are not "improvements" but
> radical design changes.

Eh?  I think of them as moderate and incremental improvements, in a
direction that Python is already moving in.  Radical would be
something like a full-scale static type system.

> I really wonder why peoples that seems to dislike one of the central
> features of Python - it's dynamism - still use it (assuming of
> course they are free to choose another language).

I certainly don't think dynamism is central to Python.  In what I see
as well-developed Python programming style, it's something that is
only rarely used in any important way.  I'd spend much less time
debugging if I got compiler warnings whenever I used dynamism without
a suitable annotation.  The 1% of the time where I really want to use
dynamism I don't see any problem with putting in an appropriate
decorator, superclass, or whatever.
--
http://mail.python.org/mailman/listinfo/python-list


Re: ctype problem

2009-01-13 Thread Aaron Brady
On Jan 13, 10:22 am, Grimson  wrote:
> hello out there,
> I have a problem with c-types.
> I made a c-library, which expects a pointer to a self defined structure.
>
> let the funtion call myfunction(struct interface* iface)
>
> and the struct:
> struct interface
> {
>     int a;
>     int b;
>     char *c;
>
> }
>
> the Python ctype port of this structur would be:
>
> class INTERFACE(Structure):
>     _fields_ = [("a"         c_int),
>                       ("b",        c_int),
>                       ("c",         c_char)]
>
> in my python-struct a create a instance of INTERFACE
>
> myiface = INTERFACE()
> myiface.a = ctypes.c_int(80)
> myiface.b = ctypes.c_int(22)
> ...
> than I make a pointer onto it.
> p_iface = ctypes.pointer(myiface)
> and I tried it also with a reference
> r_iface = ctypes.byref(myiface)
>
> but neither myclib.myfunction(p_iface) nor myclib.myfunction(r_iface)
> works properly. The function is been called but it reads only zeros (0)
> for each parameter (member in the struct).
>
> Where is my fault?
>
> Thank you..
>
> sincerely chris

Did you remember to define myclib.myfunction.argtypes= [ INTERFACE ] ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Ternary operator and tuple unpacking -- What am I missing ?

2009-01-13 Thread John Machin
On Jan 13, 5:36 pm, Steve Holden  wrote:
> Miles wrote:
> > On Tue, Jan 13, 2009 at 12:02 AM, imageguy  wrote:
> >> Using py2.5.4 and entering the following lines in IDLE, I don't really
> >> understand why I get the result shown in line 8.
>
> >> Note the difference between lines 7 and 10 is that 'else' clause
> >> result enclosed in brackets, however, in line 2, both the 'c,d'
> >> variables are assign correctly without the brackets being required.
>
> >> 1) >>> n = None
> >> 2) >>> c,d = n if n is not None else 0,0
> >> 3) >>> print c,d, type(c), type(d)
> >> 4) 0 0  
>
> > The ternary expression has higher precedence than the comma, so the
> > actual effect of line 2 (and 8) is:
>
>  c, d = (n if n is not None else 0), 0
>
> > Or written more explicitly:
>
>  c = n if n is not None else 0
>  d = 0
>
> > So the only correct way to write the expression, for the result you
> > want, is to use your line 10:
>
> >> 10)  >>> c,d = n if n is not None else (0,0)
>
> > But if you're struggling with the precedence issues, I'd recommend
> > ditching ternary expressions altogether and using full conditional
> > blocks.
>
> Yet another great example of why Guido was right to resist putting
> conditional expressions into Python for so long (and wrong to succumb to
> the demand).

"""I thought I said "Nobody mention the war!" """

IMO this is just an example of why (1) in general people who are
unsure of operator precedence should use parentheses and (2) in
particular it's not a good idea to try to write tuples without
parentheses in any but the simpler cases like a, b = b, a

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


Re: Standard IPC for Python?

2009-01-13 Thread Aaron Brady
On Jan 13, 2:04 pm, Laszlo Nagy  wrote:
> - create a wrapper, using ctypes, /windll / cdll/ to access API functions
> - use CreateFileMapping on the page file to create shared memory (a la
> windows:http://msdn.microsoft.com/en-us/library/aa366537.aspx)
> - use CreateEvent/WaitForSingleObject for signaling
> (http://msdn.microsoft.com/en-us/library/ms682396(VS.85).aspx)
> - these should be enough to implement shared memory functions and
> message queues under windows, and that might be a quick solution at
> least for me.
> - it might also be used to emulate the same posix_ipc interface, without
> any external dependency added (cygwin).
>
> All I care about is to create a working message queue. But if you think
> that this ctypes hack would be useful for other users, then I can try to
> implement it.
>
> I must tell you that I'm not very familiar with C programming (it was a
> long time ago...) and I do not own MSVC.
>
> (Hmm, can I compile this with mingw?)
>
> Laszlo

Yes.  The flags in the Extending/Embedding C++ section work with
mingw.

You can create inheritable pipes with the CreatePipe API.  'mmap'
provides shared memory, and it's a standard module.  You may also like
the 'multiprocessing' module, which comes with Python 2.6.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Standard IPC for Python?

2009-01-13 Thread drobi...@gmail.com
On Jan 13, 2:37 pm, Philip Semanchuk  wrote:
> On Jan 13, 2009, at 2:01 PM, Laszlo Nagy wrote:
>
>
>
> >> I realize that lack of Windows support is a big minus for both of  
> >> these modules. As I said, any help getting either posix_ipc or  
> >> sysv_ipc working under Windows would be much appreciated. It sounds  
> >> like you have access to the platform and incentive to see it  
> >> working, so dig in if you like.
> > Maybe I can help with windows. I just need to figure out what to  
> > use: pipes or windows sockets?
>
> >http://msdn.microsoft.com/en-us/library/aa365574(VS.85).aspx
>
> I was suggesting getting posix_ipc or sysv_ipc to compile against a  
> compatibility library (Cygwin?) under Windows. It sounds like you're  
> proposing something totally different, no?

It's not really correct to call Cygwin a compatibility library. It's
more of a separate system.
In any case, the current version (1.5.25) does not support sem_unlink
or shm_unlink so posix_ipc does not build. Cygwin 1.7, currently under
test, will support these.  I haven't tried it yet. I expect it will
work OOTB.
--
http://mail.python.org/mailman/listinfo/python-list


Reminder: Calgary Python User Group - 1st Meeting tomorrow - Wed Jan 14

2009-01-13 Thread Greg
Our first meeting is tomorrow night at:

Good Earth Cafe, 1502 11 Street SW, Calgary, AB
Wed Jan 14, 7pm - 8pm

Topic: Google App Engine

http://www.google.com/calendar/event?eid=Z2Q0cDdpYmJobzVzbzZobXJxbTc2OHUxYW9fMjAwOTAxMTVUMDIwMDAwWiBhZG1pbkBweXRob25jYWxnYXJ5LmNvbQ&ctz=America/Edmonton

Google Group / mailing list:
http://groups.google.ca/group/pythoncalgary

Website:
http://www.pythoncalgary.com/

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


Re: Does Python really follow its philosophy of "Readability counts"?

2009-01-13 Thread Russ P.
On Jan 13, 9:47 am, Bruno Desthuilliers
 wrote:
> Steven D'Aprano a écrit :
>
> > On Mon, 12 Jan 2009 13:36:07 -0800, Paul Rubin wrote:
>
> >> Bruno Desthuilliers  writes:
> >>> Why on earth are you using Python if you don't like the way it work ???
> >> Why on earth keep releasing new versions of Python if the old ones are
> >> already perfect?
>
> > That's a fallacious argument. Nobody is arguing that any specific version
> > of Python is perfect, but clearly many people do like the general design
> > choices of the language, that is, the way it works.
>
> Thanks for making my point clear.
>
> > *If* you don't like the way it works, and you have a choice in the
> > matter, perhaps you should find another language that works more the way
> > you would prefer.
>
> > On the other hand... Bruno's question is unfair. It is perfectly
> > reasonable to (hypothetically) consider Python to be the best *existing*
> > language while still wanting it to be improved (for some definition of
> > improvement).
>
> And that's the problem : what Paul suggests are not "improvements" but
> radical design changes. The resulting language - whatever it may be
> worth, I'm not making any judgement call here - would not be Python
> anymore.
>
> > Just because somebody has criticisms of Python, or a wish-
> > list of features, doesn't mean they hate the language.
>
> There's probably a whole range of nuances between "not liking" and
> "hating". And Paul is of course perfectly right to think that a language
> having this and that features from Python, but not this other one, would
> be a "better" language (at least according to it's own definition of
> "better"). Where I totally disagree is that it would make *Python* better.
>
> Also, my question was not that "unfair" (even if a bit provocative). I
> really wonder why peoples that seems to dislike one of the central
> features of Python - it's dynamism - still use it (assuming of course
> they are free to choose another language). And FWIW, I at least had a
> partial answer on this.

I think the issue here is the distinction between hacking and software
engineering. I may be misusing the term "hacking," but I do not mean
it in a pejoritive sense. I just mean getting things done fast without
a lot of concern for safety, security, and long-term maintainability
and scalability. I'm not a computer scientist, but it seems to me that
Python is great for hacking and good for software engineering, but it
is not ideal for software engineering.

What Paul is suggesting, I think, is that Python should move in the
direction of software engineering. Whether that can be done without
compromising its hacking versatility is certainly a valid question,
but if it can be done, then why not do it?

Certainly one basic principle of software engineering is data
encapsulation. Tacking new attributes onto class instances all over
the place may be convenient and useful in many cases, but it is not
consistent with good software engineering. If the programmer could
somehow disallow it in certain classes, that could be useful,
providing that those who wish to continue doing it would be free to do
so. If class attributes could somehow be declared private, that would
be useful too. Optional explicit type declarations could also be
useful -- and I believe Python does have that now, so no need to argue
about that.

Why do I continue to use Python when I have so many "complaints" about
it? As everyone here knows, it has many good qualities. My work falls
somewhere in the middle between "hacking" and software engineering. I
am developing a research prototype of a safety-critical system. A
research prototype is not safety-critical itself, and it needs to be
flexible enough to try new ideas quickly, but it also needs to serve
as a model for a well-engineered system. Is Python the right choice? I
think so, but I don't know for sure.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Read binary file and dump data in

2009-01-13 Thread Chris Rebert
On Tue, Jan 13, 2009 at 12:02 PM, Santiago Romero  wrote:
>
>  Hi.
>
>  Until now, all my python programs worked with text files. But now I'm
> porting an small old C program I wrote lot of years ago to python and
> I'm having problems with datatypes (I think).
>
>  some C code:
>
>  fp = fopen( file, "rb");
>  while !feof(fp)
>  {
>value = fgetc(fp);
>printf("%d", value );
>  }
>
>  I started writing:
>
>  fp = open(file, "rb")
>  data = fp.read()
>  for i in data:
>   print "%d, " % (int(i))
>
>  But it complains about i not being an integer... . len(data) shows
> exactly the file size, so maybe is a "type cast" problem... :-?
>
>  What's the right way to work with the binary data (read 1 byte values
> and work with them, dumping them as an integer in this case)?

Albert already pointed out the problem with using int(), so I'll just
say that you might be interested in the `struct` module:
http://docs.python.org/library/struct.html

Cheers,
Chris

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


Re: Ternary operator and tuple unpacking -- What am I missing ?

2009-01-13 Thread imageguy
On Jan 13, 1:01 am, Miles  wrote:
> On Tue, Jan 13, 2009 at 12:02 AM, imageguy  wrote:
> > Using py2.5.4 and entering the following lines in IDLE, I don't really
> > understand why I get the result shown in line 8.
>
> > Note the difference between lines 7 and 10 is that 'else' clause
> > result enclosed in brackets, however, in line 2, both the 'c,d'
> > variables are assign correctly without the brackets being required.
>
> > 1) >>> n = None
> > 2) >>> c,d = n if n is not None else 0,0
> > 3) >>> print c,d, type(c), type(d)
> > 4) 0 0  
>
> The ternary expression has higher precedence than the comma, so the
> actual effect of line 2 (and 8) is:
>
> >>> c, d = (n if n is not None else 0), 0
>
> Or written more explicitly:
>
> >>> c = n if n is not None else 0
> >>> d = 0
>
> So the only correct way to write the expression, for the result you
> want, is to use your line 10:
>
> > 10)  >>> c,d = n if n is not None else (0,0)
>
> But if you're struggling with the precedence issues, I'd recommend
> ditching ternary expressions altogether and using full conditional
> blocks.
>
> -Miles

Thanks.
Hadn't thought through the operator precedence and the affect of the
comma.
This was the first time I tried to use with tuples, so will be more
careful next time
or stick to control blocks.

g.

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


  1   2   >