[ANN] ASTNG 0.13

2005-10-22 Thread Sylvain Thénault
I'm pleased to announce the release of the Logilab's ASTNG package.
This package has been extracted from the logilab-common package, which
will be kept for some time for backward compatibility but will no
longer be maintained (this explains that this package is starting with
the 0.13 version number, since the fork occurs with the version
released in logilab-common 0.12).
See below for a description of what's inside...

What's new ?

* .locals  and .globals on scoped node handle now a list of references
  to each assigment statements instead of a single reference to the
  first assigment statement.

* fix bug with manager.astng_from_module_name when a context file is
  given (notably fix ZODB 3.4 crash with pylint/pyreverse)

* fix Compare.as_string method

* fix bug with lambda object missing the type attribute

* some minor refactoring


What is astng ?
---
The aim of this module is to provide a common base representation of
python source code for projects such as pychecker, pyreverse,
pylint... Well, actually the development of this library is essentialy
governed by pylint's needs.

It extends class defined in the compiler.ast module with some
additional methods and attributes. Instance attributes are added by a
builder object, which can either generate extended ast (let's call
them astng ;) by visiting an existant ast tree or by inspecting living
object. Methods are added by monkey patching ast classes.


Home page
-
http://www.logilab.org/projects/astng

Download

ftp://ftp.logilab.org/pub/astng

Mailing list

mailto://[EMAIL PROTECTED]

-- 
Sylvain Thénault   LOGILAB, Paris (France).

http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org

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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


ANN: Speedometer 2.0 - bandwidth and download monitor

2005-10-22 Thread Ian Ward
Announcing Speedometer 2.0
--

Speedometer home page:
  http://excess.org/speedometer/

Download:
  http://excess.org/speedometer/speedometer.py


New in this release:


  - New full-console bar graph display based on Urwid 0.8.9
  
  - Realigned graphic scale to more common units


About Speedometer
=

Speedometer is a console bandwidth and file download progress monitor with
a logarithmic bandwidth display and a simple command-line interface.

Speedometer requires Python 2.1 or later and Urwid 0.8.9 or later for
full-console bar graph display.

Speedometer is released under the GNU LGPL.
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


[ANN] PyLint 0.8

2005-10-22 Thread Sylvain Thénault
Hi there !

I'm very pleased to announce the new 0.8 release of PyLint. I've promised
this release for a long time now, and finally got the time to do it :D.
This release includes a lot of bug fixes and enhancements. Notice that
a major change in this release is a new dependancy to the astng package
which has been extracted from logilab-common. This package is 
downloadable from http://www.logilab.org/projects/astng.

What's new ?

* check names imported from a module exists in the module (E0611),
  patch contributed by Amaury Forgeot d'Arc

* print a warning (W0212) for methods that could be a function
  (implements #9100)

* new --defining-attr-methods option on classes checker

* new --acquired-members option on the classes checker, used when
  --zope=yes to avoid false positive on acquired attributes (listed
  using this new option) (close #8616)

* generate one E0602 for each use of an undefined variable
  (previously, only one for the first use but not for the following)
  (implements #1000)

* make profile option saveable

* fix Windows .bat file,  patch contributed by Amaury Forgeot d'Arc

* fix one more false positive for E0601 (access before definition)
  with for loop such as for i in range(10): print i (test 
  func_noerror_defined_and_used_on_same_line)

* fix false positive for E0201 (undefined member) when accessing to
  __name__ on a class object
  
* fix astng checkers traversal order

* fix bug in format checker when parsing a file from a platform
  using different new line characters (close #9239)

* fix encoding detection regexp

* fix --rcfile handling (support for --rcfile=file, close #9590)


What is pylint ?


Pylint is a python tool that checks if a module satisfy a coding
standard. Pylint can be seen as another pychecker since nearly all
tests you can do with pychecker can also be done with Pylint. But
Pylint offers some more features, like checking line-code's length,
checking if variable names are well-formed according to your coding
standard, or checking if declared interfaces are truly implemented,
and much more (see http://www.logilab.org/projects/pylint/ for the
complete check list). The big advantage with Pylint is that it is
highly configurable, customizable, and you can easily write a small
plugin to add a personal feature.

The usage it quite simple :

$ pylint mypackage.mymodule


This command will output all the errors and warnings related to the
tested code (here : mypackage.mymodule), will dump a little summary at
the end, and will give a mark to the tested code.

Pylint is free software distributed under the GNU Public Licence.


Home page
-
http://www.logilab.org/projects/pylint

Download

ftp://ftp.logilab.org/pub/pylint

Mailing list

mailto://[EMAIL PROTECTED]

Enjoy !
-- 
Sylvain Thénault   LOGILAB, Paris (France).

http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org

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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: Microsoft Hatred FAQ

2005-10-22 Thread Roedy Green
On Fri, 21 Oct 2005 21:47:27 -0700, David Schwartz
[EMAIL PROTECTED] wrote or quoted :

 There is no way Microsoft could have expected the 
market to be defined in this way and no way to argue that Microsoft had any 
reason to believe their conduct was illegal.

If what they did to me in the 90s was not illegal it damn well should
have been.
-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: get a copy of a string leaving original intact

2005-10-22 Thread Fredrik Lundh
Bell, Kevin wrote:

 I ended up slicing my string into a new one, rather than trying to have
 a copy of the string to alter in one case, or leave intact in another
 case.

given that you cannot modify strings in place in Python, that comment
probably doesn't match what your code really did...

(s = f doesn't copy the string, it just binds a new name to the
existing string object.  s = s.replace doesn't modify that object;
it creates a new one, and binds the same name to that one in-
stead)

/F



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


Re: override a property

2005-10-22 Thread Robin Becker
Alex Martelli wrote:
..
 If (e.g.) __set__ needs to behave differently when applied to certain
 instances rather than others, then it had better be messed with
 (overridden) compared to property.__set__ since the latter has no such
 proviso.  Of course, your architecture as sketched below (taking
 advantage of the fact that property.__set__ always calls a certain
 callable, and you get to control that callable) is OK too.

. I think I at last got this


..
 
 Why not just fset=self.__notify_fset ?  I fail to see the added value of
 this lambda.  Anyway...:

duh just being Homerish

 def __notify_fset(self,inst,value):
 value = self._validator(value)
...
 def add(self,obs):
 self._observers.append(obs)
 
 
 ...this class only offers sets of observers *per-descriptor instance*,
 not ones connected to a specific 'inst' being observed.  My point is,
 you could add the latter pretty easily.
..

 You can, if you have a way to call, say, b.x.add_per_inst(b, obs1).
 Such as, adding within ObserverProperty:
 
   self._observers_per_inst = {}
 
 in the init, and changing the notification method to do:
 
  def __notify_fset(self,inst,value):
  value = self._validator(value)
  observers = self._observers_per_inst.get(inst)
  if not observers: observers = self._observers
  for obs in observers:
  obs(inst,self._pName,value)
  inst.__dict__[self._pName] = value
 
 and a new method add_per_inst:
 
  def add_per_inst(self, inst, obs):
  self._observers_per_inst.setdefault(inst,[]).append(obs)
 
 Of course, you most likely want to use weak rather than normal
 references here (probably to both instances and observers), but that's a
 separate issue.

..
yes I begin at last to see the full complexity of this. There are really 
three possible attachments, the descriptor, instance class and the 
instance. Since the descriptor is attached to the class or a base class 
one could argue about whether observers should be inherited etc etc, but 
perhaps that's a step too far.

Thanks to Alex and Bengt and others for clarifying a bunch of issues.
-- 
Robin Becker
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Psycopg2 date problems: Can't adapt

2005-10-22 Thread Steve Holden
Gerhard Häring wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1
 
 Steve Holden wrote:
 
I'm trying to copy data from an Access database to PostgreSQL, as the 
latter now appears to work well in the Windows environment. However I'm 
having trouble with date columns. [...]
Here's the problem in a nutshell:

  d
DateTime object for '2003-10-02 00:00:00.00' at af9be0
  ocurs.execute(DELETE FROM Lines)
 
 
 This repr looks like a mxDateTime object. psycopg does include adapters
 for mxDateTime, but in order for them to be built, the mxDateTime
 sources and headers must be made available at psycopg build time
 (because it interfaces mxDateTime at the C extension level, unlike most
 if not all other Python DB-API adapters).
 
 A quick look at its setup.py reveals a have_mxdatetime variable and a
 check that decides wether to build with mxDateTime support or not. So,
 if it does not find mxDateTime, it builds without support for it. Which
 is apparently what you're experiencing.
 
Indeed it does. I am using a pre-compiled installer. Many thanks for 
your help.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft Hatred FAQ

2005-10-22 Thread Steven D'Aprano
On Fri, 21 Oct 2005 21:47:27 -0700, David Schwartz wrote:

 
 Steven D'Aprano [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 
 That's basic economics. Something which can be allowed or ignored or even
 encouraged when done by small businesses in a competitive market can
 easily become harmful and bad for the economy when done by a monopolist or
 duopolist in an uncompetitive market.
 
 Microsoft goal is and should be their own success, not the success of 
 the economy or the market in general.

Neither I, nor you, nor the government of any nation, should care a
monkey's toss specifically for Microsoft's success. Microsoft is one
special interest, out of a potentially unbounded number of possible
players in the economy of a country and the world.

Unless you or I are specifically shareholders in Microsoft, we should not
care about their specific success; and the government should be entirely
agnostic about who are the winners and losers in an economy. The
government's role should be to ensure a level playing field, and minimum
levels of health, safety and environmental standards. There is no place
for government giving special-interests like Microsoft favours.

Society regulates where and how we park our cars: for instance, none of us
are allowed to park our car in the middle of busy road. and if we try, our
car is likely to be impounded. This is not because there is anything in
and of itself *wrong* with parking at such-and-such a place, but because
of the effect it has on others. A sensible government cares for smooth
flowing traffic on the roads, with the minimum of delays and the maximum
flow practical. Perhaps Walmart or Safeway might find it convenient to
park their trucks on public roads for any number of reasons. Too bad for
them: the benefit to them does not outweigh the loss to everyone else,
even if they don't specifically block access to their competitors.

Microsoft's behaviour over-all has been just as anti-social,
anti-competitive and harmful to the over-all running of the economy as a
hypothetical Walmart or Safeway that regularly parked their trucks in the
middle of the main road for a few hours while they unloaded.

Maybe, just maybe, if Mom  Pop's Corner Store tried it once or twice, we
could afford to turn a blind eye, especially if the disruption caused by
towing their delivery van was greater than the disruption caused by their
double-parking. Thousands of people break the law by double-parking for a
few minutes, and society doesn't collapse. But something that we can
afford to ignore when done by MP's Corner Store becomes a serious problem
if done by somebody with the economic power of Walmart, with their
thousands of deliveries by 18-wheelers every day across the country.


 Microsoft's status of a monopolist 
 is only meaningful if you define the market as desktop operating systems 
 for 32-bit x86 computers. 

That is *precisely* the market we're talking about. Not any item that
runs off electricity, not orange juice, not pork bellies, not all
computing devices, but desktop PCs. What did you think the Justice
Department's investigation was about? Motor vehicles?


 There is no way Microsoft could have expected the 
 market to be defined in this way and no way to argue that Microsoft had any 
 reason to believe their conduct was illegal.

Microsoft have lawyers. Microsoft destroyed emails and at least one senior
manager perjured himself in court. Microsoft created a fake video
demonstration which they then gave as evidence. Do you really believe that
Microsoft's executives are so incompetent that they don't get legal advice
before writing up contracts? Or that nobody in authority at Microsoft
realised that destroying evidence and lying to a judge are crimes?

In any case, even if you are right that Microsoft had no ideas... so what?
Ignorance of the law never has been an excuse for criminal behaviour. It
has always been every individual's responsibility to make sure that they
do not act illegally, and that goes for companies as well. 



-- 
Steven.

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


[ANN] ASTNG 0.13

2005-10-22 Thread Sylvain Thénault
I'm please to announce the release of the Logilab's ASTNG package.
This package has been extracted from the logilab-common package, which
will be kept for some time for backward compatibility but will no
longer be maintained (this explains that this package is starting with
the 0.13 version number, since the fork occurs with the version
released in logilab-common 0.12).
See below for a description of what's inside...

What's new ?

* .locals  and .globals on scoped node handle now a list of references
  to each assigment statements instead of a single reference to the
  first assigment statement.

* fix bug with manager.astng_from_module_name when a context file is
  given (notably fix ZODB 3.4 crash with pylint/pyreverse)

* fix Compare.as_string method

* fix bug with lambda object missing the type attribute

* some minor refactoring


What is astng ?
---
The aim of this module is to provide a common base representation of
python source code for projects such as pychecker, pyreverse,
pylint... Well, actually the development of this library is essentialy
governed by pylint's needs.

It extends class defined in the compiler.ast module with some
additional methods and attributes. Instance attributes are added by a
builder object, which can either generate extended ast (let's call
them astng ;) by visiting an existant ast tree or by inspecting living
object. Methods are added by monkey patching ast classes.


Home page
-
http://www.logilab.org/projects/astng

Download

ftp://ftp.logilab.org/pub/astng

Mailing list

mailto://[EMAIL PROTECTED]

-- 
Sylvain Thénault   LOGILAB, Paris (France).

http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org

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


[ANN] PyLint 0.8

2005-10-22 Thread Sylvain Thénault
Hi there !

I'm very please to announce the new 0.8 release of PyLint. I've promised
this release for a long time now, and finally got the time to do it :D.
This release includes a lot of bug fixes and enhancements. Notice that
a major change in this release is a new dependancy to the astng package
which has been extracted from logilab-common. This package is 
downloadable from http://www.logilab.org/projects/astng.

What's new ?

* check names imported from a module exists in the module (E0611),
  patch contributed by Amaury Forgeot d'Arc

* print a warning (W0212) for methods that could be a function
  (implements #9100)

* new --defining-attr-methods option on classes checker

* new --acquired-members option on the classes checker, used when
  --zope=yes to avoid false positive on acquired attributes (listed
  using this new option) (close #8616)

* generate one E0602 for each use of an undefined variable
  (previously, only one for the first use but not for the following)
  (implements #1000)

* make profile option saveable

* fix Windows .bat file,  patch contributed by Amaury Forgeot d'Arc

* fix one more false positive for E0601 (access before definition)
  with for loop such as for i in range(10): print i (test 
  func_noerror_defined_and_used_on_same_line)

* fix false positive for E0201 (undefined member) when accessing to
  __name__ on a class object
  
* fix astng checkers traversal order

* fix bug in format checker when parsing a file from a platform
  using different new line characters (close #9239)

* fix encoding detection regexp

* fix --rcfile handling (support for --rcfile=file, close #9590)


What is pylint ?


Pylint is a python tool that checks if a module satisfy a coding
standard. Pylint can be seen as another pychecker since nearly all
tests you can do with pychecker can also be done with Pylint. But
Pylint offers some more features, like checking line-code's length,
checking if variable names are well-formed according to your coding
standard, or checking if declared interfaces are truly implemented,
and much more (see http://www.logilab.org/projects/pylint/ for the
complete check list). The big advantage with Pylint is that it is
highly configurable, customizable, and you can easily write a small
plugin to add a personal feature.

The usage it quite simple :

$ pylint mypackage.mymodule


This command will output all the errors and warnings related to the
tested code (here : mypackage.mymodule), will dump a little summary at
the end, and will give a mark to the tested code.

Pylint is free software distributed under the GNU Public Licence.


Home page
-
http://www.logilab.org/projects/pylint

Download

ftp://ftp.logilab.org/pub/pylint

Mailing list

mailto://[EMAIL PROTECTED]


Enjoy !
-- 
Sylvain Thénault   LOGILAB, Paris (France).

http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org

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


Re: C replacement for Queue module

2005-10-22 Thread Peter Hansen
Jonathan Ellis wrote:
 I'm working on an application that makes heavy use of Queue objects in
 a multithreaded environment.
 
 By heavy I mean millions of calls to put and get, constituting ~20%
 of the app's run time.  The profiler thinks that a significant amount
 of time is spent in this code -- not just a consumer waiting for a
 producer, but actual _empty, notify calls, etc.

I wonder if the use case would support hand-crafting an alternative. 
Queues appear fairly heavy weight (when you look at the implementation), 
and while they are very robust, if your own needs allow putting many 
items in at the same time, or getting many items out, for example, then 
perhaps you could come up with a much faster alternative based on the 
primitives (e.g. Event, Condition, etc) and perhaps some wrapped data 
structure other than the list that Queues use.

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


Re: A question about searching with multiple strings

2005-10-22 Thread Steven D'Aprano
On Fri, 21 Oct 2005 13:39:17 -0700, googleboy wrote:

 
 Hi there.
 
 I have defined a class called Item with several (about 30 I think)
 different attributes (is that the right word in this context?).  An
 abbreviated example of the code for this is:
 
 class Item(object):
 
   def __init__(self, height, length, function):
   params = locals()
   del params['self']
   self.__dict__.update(params)

I get very worried when I see code like that. It makes me stop and think
about what it does, and why you would want to do it. I worry about hidden
side effects. Instead of just groking the code instantly, I've got to stop
and think. You're taking a copy of the locals, deleting self from it, and
them updating self's dictionary with them... why? What do you hope to
achieve?

If I were project manager, and one of my coders wrote something like this,
I would expect him or her to have a really good reason for it. I'd be
thinking not only of hidden bugs (what if there is something in locals
you don't expect?), but every time a developer has to work on this class,
they have to stop and think about it.

Joel (of Joel On Software fame) talks about code looking wrong and
smelling dirty. This code might work. It might be perfectly safe. But
there's a whiff to this code.

http://www.joelonsoftware.com/articles/Wrong.html



   def __repr__(self):
   all_items = self.__dict__.items()
   return '%s,%s,%s' % (self.height, self.length, self.function)

You aren't using all_items. Why waste a lookup fetching it?

 I have a csv file that I use to store and retrieve all the info about
 each Item, one item per line.

Would you like to give us a couple of examples of items from the CSV file?


 I have written a little peice of python that lets me search through all
 Items (after reading them into a variable called all_items) and will
 return matching results:
 
 
 
 for item in all_items:
 
   strItem = str(item)
 
   m = re.search(p[i], strItem, flags = re.I)
   if m:
   height = getattr(item, height)
   length = getattr(item, length)
   function = getattr(item, function)
   print height is %s, length is %s and function is %s % height,
 length, function

And here we why global variables are Bad: without knowing what p is, how
are we supposed to understand this code?

 This has the limitation of only working over a single search item.

So you are searching items for items... I think you need to use a better
name for your class. What does class Item actually represent?

 I
 want to be able to search over an uncontrollable number of search
 strings because I will have people wanting to search over 2, 3 or even
 (maybe) as many as 5 different things.

 I was thinking that I would try to write a function that created a
 sublist of Items if it matched and then run subsequent searches over
 the subsequent search strings using this sublist.

That might work.
 
 I am not entirely sure how to store this subset of Items in such a way
 that I can make searches over it.

How about in a list?

 I guess I have to initialize a
 variable of type Item, which I can use to add matching Item's to,  but
 I have no idea how to do that(If it was just a list I could say
 sublist = [],  what do I use for self defined classes?  

See my next post (to follow).

 I Am also
 usure how to go about creating a function that will accept any number
 of parameters.

def func1(*args):
for arg in args:
print arg

def func2(mandatory, *args):
print Mandatory, mandatory
for arg in args:
print arg

Does that help?



-- 
Steven.

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


Re: A question about searching with multiple strings

2005-10-22 Thread Steven D'Aprano
On Fri, 21 Oct 2005 13:39:17 -0700, googleboy wrote:

 Hi there.
 
 I have defined a class called Item with several (about 30 I think)
 different attributes (is that the right word in this context?).

Generally speaking, attributes shouldn't be used for storing arbitrary
items in an object. That's what mapping objects like dicts are for. I
would change your class so that it no longer mucked about with it's
internal __dict__:

class Item():
def __init__(self, height, length, function, **kwargs):
# assumes that ALL items will have height, length, function
# plus an arbitrary number (may be zero) of keyword args
self.height = height
self.length = length
self.function = function
self.data = kwargs  # store custom data in an instance attribute,
# NOT in the object __dict__


You would use it something like this:

def create_items():
all_items = []
# WARNING WARNING WARNING
# pseudo-code -- this doesn't work because I don't
# know what your input file looks like
open input file
for record in input file:
h = read height
l = read length
f = read function
D = {}
for any more items in record:
D[item key] = item value
newitem = Item(h, l, f, D)
all_items.append(newitem)
close input file
return all_items

Now you have processed your input file and have a list of Items. So let's
search for some!

Firstly, create a function that searches a single Item:

def SearchOneOr(source, height=None, length=None, \
function=None, **kwargs):
Performs a short-circuit OR search for one or more search term.
if height is not None:
if source.height == height: return True
if length is not None:
if source.length == length: return True
if function is not None:
if source.function == function: return True
for key, value in kwargs:
if source.data.has_key(key) and source.data[key] == value:
return True
return False

def SearchOneAnd(source, height=None, length=None, \
function=None, **kwargs):
Performs a short-circuit AND search for one or more search term.
if height is not None:
if source.height != height: return False
if length is not None:
if source.length != length: return False
if function is not None:
if source.function != function: return False
for key, value in kwargs:
if source.data.has_key(key) and source.data[key] != value:
return False
else:
return False
return True


Now create a function that searches all items:

def SearchAll(source_list, flag, height=None, length=None, \
  function=None, **kwargs):
found = []
if flag:
search = SearchOneOr
else:
search = SearchOneAnd
for source in source_list:
if search(source, height, length, function, kwargs):
found.append(source)
return found

Now pass all_items to SearchAll as the first argument, and it will search
through them all and return a list of all the items which match your
search terms.

Hope this helps.


-- 
Steven.

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


Re: best way to replace first word in string?

2005-10-22 Thread Steven D'Aprano
On Thu, 20 Oct 2005 10:25:27 -0700, Micah Elliott wrote:

 I thought that string concatenation was rather
 expensive, so its being faster than %-formatting surprised me a bit:

Think about what string concatenation actually does: 

s = hello  + world

In pseudo-code, it does something like this:

- Count chars in hello (six chars).
- Count chars in world (five chars).
- Allocate eleven bytes.
- Copy six chars from hello  and five from world into the newly
allocated bit of memory.

(This should not be thought of as the exact process that Python uses, but
simply illustrating the general procedure.)

Now think of what str-formatting would do:

s = hello %s % world

In pseudo-code, it might do something like this:

- Allocate a chunk of bytes, hopefully not too big or too small.
- Repeat until done:
- Copy chars from the original string into the new string, 
until it hits a %s placeholder.
- Grab the next string from the args, and copy chars from 
that into the new string. If the new string is too small, 
reallocate memory to make it bigger, potentially moving 
chunks of bytes around.

The string formatting pseudo-code is a lot more complicated and has to do
more work than just blindly copying bytes. It has to analyse the bytes it
is copying, looking for placeholders.

So string concatenation is more efficient, right? No. The thing is, a
*single* string concatenation is almost certainly more efficient than a
single string concatenation. But now look what happens when you repeat it:

s = h + e + l + l + o +   + w + o + r + l + d

This ends up doing something like this:

- Allocate two bytes, copying h and e into them.
- Allocate three bytes, copying he and l into them.
- Allocate four bytes, copying hel and l into them.
... 
- Allocate eleven bytes, copying hello worl and d into them.

The problem is that string concatenation doesn't scale efficiently. String
formatting, on the other hand, does more work to get started, but scales
better.

See, for example, this test code:

py def tester(n):
... s1 = 
... s2 = %s * n
... bytes = tuple([chr(i % 256) for i in range(n)])
... t1 = time.time()
... for i in range(n):
... s1 = s1 + chr(i % 256)
... t1 = time.time() - t1
... t2 = time.time()
... s2 = s2 % bytes
... t2 = time.time() - t2
... assert s1 == s2
... print t1, t2
...
py x = 10
py tester(x)
3.24212408066 0.01252317428
py tester(x)
2.58376598358 0.01238489151
py tester(x)
2.76262307167 0.01474809646

The string formatting is two orders of magnitude faster than the
concatenation. The speed difference becomes even more obvious when you
increase the number of strings being concatenated:

py tester(x*10)
2888.56399703 0.13130998611

Almost fifty minutes, versus less than a quarter of a second.


-- 
Steven.

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


Re: best way to replace first word in string?

2005-10-22 Thread Steven D'Aprano
On Sat, 22 Oct 2005 21:05:43 +1000, Steven D'Aprano wrote:

 The thing is, a
 *single* string concatenation is almost certainly more efficient than a
 single string concatenation.

Dagnabit, I meant a single string concatenation is more efficient than a
single string replacement using %.


-- 
Steven.

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


Listening for a certain keypress in the background

2005-10-22 Thread Mathias Dahl
I have created a Python program that is running on my desktop. 

How can I make it listen for a certain keypress (say, Windows-key +
space) in a controlled fashion even when it is not the program having
focus?

I need to do this running GNOME under Mandrake GN/Linux 10.

/Mathias

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


Listening for keypress in the background

2005-10-22 Thread Mathias Dahl
I have created a small Python program that is running on my desktop.

How can I make it listen for a certain keypress (say, Windows-key +
space) in a controlled fashion even when it is not the program having
focus?

I need to do this running under GNOME in Mandrake GN/Linux 10.

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


Re: Listening for keypress in the background

2005-10-22 Thread Peter Hansen
Mathias Dahl wrote:
 I have created a small Python program that is running on my desktop.
 
 How can I make it listen for a certain keypress (say, Windows-key +
 space) in a controlled fashion even when it is not the program having
 focus?
 
 I need to do this running under GNOME in Mandrake GN/Linux 10.

Search Google for python keylogger.

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


C extension modules in Python

2005-10-22 Thread luiscasanova
Hello,

I'vre written an extension module to accelarate some code i've made in
python with numarray. Then i compiled an linke d it with swig, my
problem is that when i make the import in my python code it gives me an
error: ImportError: libnumarray.so: cannot open shared object file: No
such file or directory

does anyone know why this hapens and how can i solve it?

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


Re: access dictionary with preferred order ?

2005-10-22 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

 I am wondering if there is a dictionary data type that allows me to
 define the order of access when iterating it using items/keys etc. ?

 An example:

 a=dict(a=dict(), c=dict(), h=dict())
 prefer=['e','h', 'a']

 for x in a.values: print x

 would give me
 {h:dict()}, {a:dict()}, then the rest which I don't care about the
 order ?

a straight-forward implementation should be pretty efficient:

for k in prefer:
try:
v = d.pop(k)
except KeyError:
pass
else:
... deal with k, v ...
for k, v in d.iteritems():
... deal with k, v ...

or, non-destructive:

for k in prefer:
try:
v = d[k]
except KeyError:
pass
else:
... deal with k, v ...
for k, v in d.iteritems():
if k not in prefer:
... deal with k, v ...

the latter is trivial to convert into a helper generator:

def ordered_items(d, prefer):
for k in prefer:
try:
v = d[k]
except KeyError:
pass
else:
yield k, v
for k, v in d.iteritems():
if k not in prefer:
yield k, v

for k, v in ordered_items(d, prefer):
... deal with k, v ...

if you insist on having this behaviour in a type rather than a helper,
subclass dict and add ordered_items as a method.

/F



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


Re: C replacement for Queue module

2005-10-22 Thread Jason Lai
As far as Queues go, the adding/popping is apparently done with deque
which are implemented in C. The Queue class pretty much just provides
blocking operations and is otherwise a very thin layer around deque. As
far as primitives go, only threading.Lock is written in C and the
others are pure Python, so they're not that fast, which might be a
reason for Queue's slowness.

As far as writing a custom C module, you could probably leave most of
the work to deque and just implement blocking. If you stick to a simple
lock primative, you can keep it portable and use Python's abstracted
thread interface with an amazing choice of two whole functions: acquire
and release.

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


pyHook example.py brakes windows dead keys mechanisme

2005-10-22 Thread Martin P. Hellwig
Hi all,

I noticed that the dead keys* mechanism (XPSP2 NL, keyboard map US, 
input language Dutch) doesn't work when running the pyHooks (python 241) 
example.
Instead of ö (o) I immediately get o.
If I close the pyHooks example the expected behavior returns.

Is there a way how I can get both working at the same time?


-- 
mph


* typing  prints nothing the dead key, when continuing with o the 
character ö is printed, the same mechanimse applies for ' ~ ` in 
combination with most of the letters e.g. e(éëè), n(ñ), o(óõö) and c(ç).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Module Importing Question

2005-10-22 Thread Kent Johnson
James Stroud wrote:
 Hello All,
 
 I have two modules that I use interchangably depending on the circumstances. 
 These modules are imported by yet another module. I want the importation of 
 these two alternatives to be mutually exclusive and dependent on the state of 
 the outermost module
 
 A diagram:
 
 mainApp ==imports== aModule ==imports== [oneMod | orTheOtherMod]
 
 I want the importing of oneMod or orTheOtherMod to depend on the state of the 
 mainApp. aModule is frozen, as are oneMod and orTheOtherMod. How might I 
 accomplish this?

I don't know what you mean by frozen, so maybe this is no good, but I would 
avoid having aModule look back at the state of mainApp. Instead use another 
module to communicate state. This could be a simple as

# in mainApp
import helper
if something:
  import oneMod as theMod
else:
  import orTheOtherMod as theMod
helper.theMod = theMod

import aModule

# in aModule
import helper.theMod as theMod
theMod.someFunction()

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


Re: Help with language, dev tool selection

2005-10-22 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

 I have a flat text file, 3 records, each record has two columns,
 the columns are tab separated.

 The file looks like this (approximately)

 Sarajevo 431104-133111

(when did they move sarajevo to italy?)

 Mostar 441242-133421
 Zagreb 432322-134423

here's a straightforward Python solution:

HEADER = This page displays longitude-latitude information
SUBHEADER = Grad

for line in open(datafile.txt):

town, latlong = line.split()
lat, long = latlong.split(-)

f = open(town + .html, w)
f.write(HEADER + \n)
f.write(SUBHEADER + \n)
f.write(town + \n)
f.write(long +   + lat + \n)
f.close()

# end

tweak as necessary.  see the Python tutorial for help:

http://docs.python.org/tut/tut.html

/F



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


Re: python problems with dos lineendings in python-scripts

2005-10-22 Thread Steve Holden
marco wrote:
 hi folks,
 
 i can not run any python scripts with dos lineendings under cygwin's python.
 if i run such a scripts i get stupid syntax error messages from python.
 
 what can i do to run these scripts without changing the lineending of these 
 scripts.
 
 regards marco
 
The only time line endings will make a difference is if there's a 
carriage return on the shebang line. If you run the script using

   python script.py

you should find that you get no problems at all.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: override a property

2005-10-22 Thread Kay Schluehr
Robin Becker wrote:
 Kay Schluehr wrote:
  Robin Becker wrote:
 
 
 I thought that methods were always overridable.
 In this case the lookup on the
 class changes the behaviour of the one and only property.
 
 
  How can something be made overridable that is actually overridable? I
  didn't know how to better express the broken polymorphism of Pythons
  properties than by stating it as a pleonasm about the used get and set
  methods. This way a property don't ever have to be redefined in
  subclasses if get_x, set_x etc. are changed.
 
  Kay
 

 well I guess that's the ambiguity of human language. Clearly when I
 assign to a normal attribute I am changing its value; assigning to a
 property or descriptor does something that is not so obvious. Changing
 the behaviour of such an attribute could be done by inheritance as
 suggested. The new class has overridden the property. When I want to do
 that on an instance I have first to create a mutable version of the
 descriptor where the mutability is on the instance not the class. I call
 the action of changing the base descriptor behaviour 'overriding', but
 perhaps that's not the correct word. What do you suggest?
 --
 Robin Becker

I would suggest to take a step back and start with Raymond Hettingers
descriptor definition:

In general, a descriptor is an object attribute with binding
behavior, one whose attribute access has been overridden by methods in
the descriptor protocol. Those methods are __get__, __set__, and
__delete__. If any of those methods are defined for an object, it is
said to be a descriptor.

http://users.rcn.com/python/download/Descriptor.htm

The definition is a little confusing since we have to identify the
descriptor object that implements one of the descriptor methods
__get__, __set__ and __del__ with an object attribute that is assigned
by the descriptor ( as object not attribute ). Otherwise we can assert
that a descriptor becomes effective only if it is used as an object
attribute. The meaning / essence of a descriptor is to assign
attributes by a descriptor to alter binding behaviour but it's
essentially an object that can be handled quite differently. To make
the destinction clear I will talk about descripted attributes.

Now we can talk unambigously about overriding the descriptor by means
of overriding the descriptor methods in subclasses. In case of
properties we pass certain functions into property() that will be
wrapped into descriptor methods. Thereby property() is itself a
descriptor. If we use methods of the class where the descripted
attribute is defined, overriding has no effect on the descriptor. The
inheritance hierarchies of descriptors and classes that define
descripted attributes do not correspond.

One way of establishing a pseudo-correspondence I've already presented.
But maybe one can do it better without decorators? Remember that
property() is a descriptor factory and there is no intrinsic need to
pass functions into a factory function. Why not passing strings that
are names of methods?

For brevity only __get__ should be defined here:

class described_by(object):
def __init__(self, fget=):
assert isinstance(fget, str)
self.fget = fget

def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError, unreadable attribute
return getattr(obj.__class__, self.fget)(obj)


class A(object):
def __init__(self, x):
self._x = x

def get_x(self):
return self._x

x = described_by(get_x)

class B(A):
def get_x(self):
return self._x**2

 a = A(7)
 a.x
7
 b = B(7)
 b.x
49

Regards,
Kay

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


Re: best way to replace first word in string?

2005-10-22 Thread Chris F.A. Johnson
On 2005-10-22, William Park wrote:
 [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 I am looking for the best and efficient way to replace the first word
 in a str, like this:
 aa to become - /aa/ to become
 I know I can use spilt and than join them
 but I can also use regular expressions
 and I sure there is a lot ways, but I need realy efficient one

 I doubt you'll find faster than Sed.

   On the contrary; to change a string, almost anything will be faster
   than sed (except another external program).

   If you are in a POSIX shell, parameter expansion will be a lot
   faster.

   In a python program, one of the solutions already posted will be
   much faster.

-- 
Chris F.A. Johnson http://cfaj.freeshell.org
==
Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress
http://www.torfree.net/~chris/books/cfaj/ssr.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Listening for keypress in the background

2005-10-22 Thread Mathias Dahl
Peter Hansen [EMAIL PROTECTED] writes:

 How can I make it listen for a certain keypress (say, Windows-key +
 space) in a controlled fashion even when it is not the program having
 focus?
 
 I need to do this running under GNOME in Mandrake GN/Linux 10.

 Search Google for python keylogger.

Thanks, good idea! The relevant pages I found only link to
Windows-specific keyloggers though.

I just got another idea on a solution for my main problem (invoking my
sleeping app) and that would be to let my window manager execute a
small invoker program that would communicate with the sleeping
app. The question is, which is the easiest way to communicate with a
running Python program? Signals? TCP/IP (not really, right?) Pipes?

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


Re: How to get a raised exception from other thread

2005-10-22 Thread dcrespo
 One suggestion about the above: description is actually the exception
 instance (the object), not just the description.

Yes. In fact, it's a tuple. Maybe, I'll change it for just printing the
second item of it.

Thanks a lot.

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


PID and/or handle assistance. . .?

2005-10-22 Thread Michael Williams
Hi All,

Can anyone explain how to both spawn processes from PYTHON and  
acquire their process IDs or a handle to them for use later?  I'd  
also like to acquire the stdout of each spawned process.

Regards,
Mike


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


Re: PID and/or handle assistance. . .?

2005-10-22 Thread Diez B. Roggisch
Michael Williams wrote:
 Hi All,
 
 Can anyone explain how to both spawn processes from PYTHON and  acquire 
 their process IDs or a handle to them for use later?  I'd  also like to 
 acquire the stdout of each spawned process.

Google dead today? Well, check out the modules subprocess, popen2 and os.

Regards,

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


Re: Python variables are bound to types when used?

2005-10-22 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

  reset your brain:
 
  http://effbot.org/zone/python-objects.htm

 Neat link.

 Can you expand on this:

  a type (returned by type(x))
 ...
  You cannot change the type.

the page was written before the type/class unification in Python 2.2,
at a time where the word type had a stricter meaning (referring to C-
level types, not user-level classes).

in CPython 2.2 and later, you can in fact change the type under some
circumstances, as long as the internal structure (the C-level type) is
identical.  the types involved must (to quote the checkin messages):

- have the same basic size
- have the same item size
- have the same dict offset
- have the same weaklist offset
- have the same GC flag bit
- have a common base that is the same except for maybe the
  dict and weaklist (which may have been added separately at
  the same offsets in both types)
- both be heap types

this basically limits the feature to classes defined at the Python level
(just like before the unification); most attempts to use arbitrary types
will fail.  e.g.

 x.__class__ = dict
Traceback (most recent call last):
  File stdin, line 1, in ?
TypeError: __class__ assignment: only for heap types

 class c(list):
... pass
...
 x.__class__ = c
Traceback (most recent call last):
  File stdin, line 1, in ?
TypeError: __class__ assignment: 'a' object layout differs from 'c'

I suppose it's time to add a footnote to the objects page...

/F



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


Re: subprocess exiting in an incomprehensible fashion

2005-10-22 Thread Will
Well, I'll be damned... Thank you very much. I'm still getting a little
tripped up with blocking IO and whatnot, but I think I can work that
out. This was a real help, thanks again.

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import subprocess
import random
import re
import os
import time
import select

calc = subprocess.Popen(dc, stdin=subprocess.PIPE,
  stdout=subprocess.PIPE,
  stderr=subprocess.STDOUT)
max = random.Random().randint(10, 100)
for value in range(1, max):
calc.stdin.write(%d\n % value)
if value  1:
calc.stdin.write(*\n)
calc.stdin.write(p\n)

select.select([calc.stdout.fileno()], [], [])
time.sleep(.1) # Still not always getting the result

string = os.read(calc.stdout.fileno(), 500)

print String: , string
dcproduct, repcount = re.subn(\\\|\\s, , string)
dcproduct = int(dcproduct)
pyproduct = reduce(lambda x,y: x * y, range(1, max))
if dcproduct == pyproduct:
print Π(1,%d): % (max - 1)
else:
print Products don't match: n = %d % (max - 1)
print   %d % dcproduct
print   %d % pyproduct

calc.stdin.write(q\n)
status = calc.wait()
print Exited with: %d % status

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

Zope and Persistence

2005-10-22 Thread ryankaskel
I don't know if this is the appropriate place to post a Zope question
but I figure many here are familiar with it. I'm confused about the
role of the ZMI when it comes to development. I want to write a simple
script that logs page hits. I wrote it in what was called a Script
(Python) resource in the ZMI. When I access the page it gives an error
saying that this file cannot import Persistence, etc. This makes sense
but where would I put this script and how would I invoke it? It is only
supposed to store an integer in Data.fs. Thanks.

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


find() method in ElementTree

2005-10-22 Thread mirandacascade
I do not understand how to use the find() method in ElementTree.

The file 'sample.xml' is:

?xml version=1.0?
SampleRoot
Header
ProductFindMystery/Product
/Header
SpecificInformation
SampleDetailabc/SampleDetail
/SpecificInformation
/SampleRoot

 from elementtree.ElementTree import ElementTree
 doc = ElementTree(file='sample.xml')
 iterList = doc.getiterator()
 iterList
[Element SampleRoot at 1166850, Element Header at 1166878, Element
Product at 11668a0, Element SpecificInformation at 1166940, Element
SampleDetail at 1166990]
 len(iterList)
5
 element = iterList[4]
 element.tag
'SampleDetail'
 x = doc.find('SampleDetail')
 if x == None:
... print 'x is none'
...
x is none


The ElementTree documentation indicates that:
find(pattern) returns the first subelement that matches the given
pattern, or None if there is no matching element.

and

the pattern argument can either be a tag name, or a path expression

Based on the following snippet from the interactive window:

 doc = ElementTree(file='sample.xml')
 iterList = doc.getiterator()
 element = iterList[4]
 element.tag
'SampleDetail'

I inferred (perhaps incorrectly) that within doc there is a subelement
with a tag 'SampleDetail'.

Based on the following snippet:

 x = doc.find('SampleDetail')
 if x == None:
... print 'x is none'
...
x is none

I conclude that there is no subelement in doc with a tag
'SampleDetails'.

My questions:
1) in the example above is there a subelement of doc with a tag
'SampleDetails'?
2) if so, what is the proper way of writing the call to the find()
method to locate that subelement?

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


UI Design, XUL, Blender

2005-10-22 Thread Terry Hancock
Newcomers to Blender (3D modelling/animation program)
often find its fairly unique UI a bit off-putting,
but on closer inspection, I find it's a very compelling
design for power users (i.e. professionals who need to
use a given program on a daily basis, and who are therefore
willing to make the effort to learn the specific interface).
It is much better than either a command line interface
or a more conventional GUI, for that purpose, IMHO.

Unfortunately, Blender doesn't really follow a Model-View-
Controller design, so I'm not sure how separable the
interface is from the rest of the program (I'm asking that
question elsewhere). My question here, is just how unique,
really, is that interface?  Could it be implemented with
standard GUI toolkits (using complex widgets and
customizing button appearance, for example)?

The main things I notice as a user are that:

* The buttons are smaller and use iconic graphics, so you
  can access more controls at once.

* Extensive use of tabs allowing control pallettes to be
  brought up or expanded, facillitating highly hierarchical
  pallettes.

* Widgets are color-coded as to functionality and fall into
  several important categories:

  o ON/OFF (Bistate)
  o ON/OFF/FLOATING (Tristate)
  o Numerical data entry, which act simultaneously as
sliders and data-entry widgets

* The main thing is that these buttons actually have
  fairly complicated behavior, acting as sliders,
  text-entry, and selectboxes simultaneously.

(I may be missing things that would be more apparent to GUI
designers, though, so I'd be even more interested in a reply
from someone who's actually seen the Blender UI themselves.)

I'm wondering if this could be achieved in a Python program
by using wxPython or PyGTK or another popular, 
cross-platform GUI toolkit?  Also, is a GUI specification
language like XUL capable of expressing this kind of 
interface so that it could be made functional on multiple
GUI implementations?

I'm trying to compare two alternatives:

1) Figure out how to mimic the Blender GUI in a more
   conventional, separable GUI toolkit, so that an MVC
   design can be more easily used.  (This leaves a fairly
   complication View component, but there are other fairly
   advanced 3D visualization components).

2) Use Blender itself, using the Python scripting facility
   to wedge an MVC design into it (probably by hacking
   Blender to create a bridge between Blender's internal
   (C struct based) model, and an external model (probably
   represented in an object database component, such
   as ZODB).

in order to figure out which would be easier.

Any more informed comments from people who know the various
GUI packages would be a lot of help.  I assume it goes
without saying that I'm looking at Python as an integration
language.  In my ideal design, the M,V, and C components
are separate Python modules, so that the communications
are all at the Python level.

Cheers,
Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Missing modules '_ssl', 'ext.IsDOMString', 'ext.SplitQName'

2005-10-22 Thread uid09012_ti

Hi,

i get the following error message when i use py2exe on my application:

The following modules appear to be missing
['_ssl', 'ext.IsDOMString', 'ext.SplitQName']

I've installed PyXML-0.8.4.win32-py2.4.exe. My version of python is 2.4
I've checked in the pyxml directories and these modules are not there.

Anybody have an idea what I'm doing wrong?

Thanks,
Martin.

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


Re: find() method in ElementTree

2005-10-22 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

 My questions:
 1) in the example above is there a subelement of doc with a tag
 'SampleDetails'?

find only searches for direct subelements; SampleDetail is not a direct
subelement to SampleRoot, since there's a SpecificInformation element
in between.

 2) if so, what is the proper way of writing the call to the find()
 method to locate that subelement?

elem = doc.find(.//SampleDetail)

should work.

/F



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


any good midi tutorials?

2005-10-22 Thread malik
anybody know any good midi tutorials for python?
i am trying to make a realtime midi manipulation application.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Zope and Persistence

2005-10-22 Thread Terry Hancock
On Saturday 22 October 2005 12:34 pm, [EMAIL PROTECTED] wrote:
 I don't know if this is the appropriate place to post a Zope question
 but I figure many here are familiar with it.

You will do much better to use the Zope users' mailing list. Go to
zope.org and follow the mailing lists link to sign up.

 I'm confused about the
 role of the ZMI when it comes to development. I want to write a simple
 script that logs page hits. I wrote it in what was called a Script
 (Python) resource in the ZMI. When I access the page it gives an error
 saying that this file cannot import Persistence, etc.

Python scripts are NOT Python modules, and you should not have to
import anything to make use of persistence. Objects you manipulate
using the ZMI interface are pretty much always objects in the ZODB
database (anything that shows up as an object or a property in
the ZMI is a persistent object).

What you want to do is add an integer property to the folder containing
the script (i.e. context or container, depending on whether you want
to maintain a count in the directory from which the script is called,
or one unique counter where the script is stored).  That's your counter.

Also, be sure to follow the help link in the ZMI and use the online
API documentation.

 This makes sense
 but where would I put this script and how would I invoke it? It is only
 supposed to store an integer in Data.fs. Thanks.

If you actually needed imports and access to the internal ZODB machinery,
then you would need to write a Product, not work in the ZMI at all.

But you don't.

Cheers,
Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

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


Re: best way to replace first word in string?

2005-10-22 Thread Mike Meyer
Steven D'Aprano [EMAIL PROTECTED] writes:
 py def tester(n):
 ... s1 = 
 ... s2 = %s * n
 ... bytes = tuple([chr(i % 256) for i in range(n)])
 ... t1 = time.time()
 ... for i in range(n):
 ... s1 = s1 + chr(i % 256)
 ... t1 = time.time() - t1
 ... t2 = time.time()
 ... s2 = s2 % bytes
 ... t2 = time.time() - t2
 ... assert s1 == s2
 ... print t1, t2
 ...
 py 
 py tester(x)
 3.24212408066 0.01252317428
 py tester(x)
 2.58376598358 0.01238489151
 py tester(x)
 2.76262307167 0.01474809646

 The string formatting is two orders of magnitude faster than the
 concatenation. The speed difference becomes even more obvious when you
 increase the number of strings being concatenated:

The test isn't right - the addition test case includes the time to
convert the number into a char, including taking a modulo.

I couldn't resist adding the .join idiom to this test:

 def tester(n):
...  l1 = [chr(i % 256) for i in range(n)]
...  s1 = 
...  t1 = time.time()
...  for c in l1:
...   s1 += c
...  t1 = time.time() - t1
...  s2 = '%s' * n
...  l2 = tuple(chr(i % 256) for i in range(n))
...  t2 = time.time()
...  s2 = s2 % l2
...  t2 = time.time() - t2
...  t3 = time.time()
...  s3 = ''.join(l2)
...  t3 = time.time() - t3
...  assert s1 == s2
...  assert s1 == s3
...  print t1, t2, t3
... 
 tester(x)
0.0551731586456 0.0251281261444 0.0264830589294
 tester(x)
0.0585241317749 0.0239250659943 0.0256059169769
 tester(x)
0.0544500350952 0.0271301269531 0.0232360363007

The order of magnitude now falls to a factor of two. The original
version of the test on my box also showed an order of magnitude
difference, so this isn't an implementation difference.

This version still includes the overhead of the for loop in the test.

The join idiom isn't enough faster to make a difference.

 py tester(x*10)
 2888.56399703 0.13130998611

 tester(x * 10)
1.22272014618 0.252701997757 0.27273607254
 tester(x * 10)
1.21779584885 0.255345106125 0.242965936661
 tester(x * 10)
1.25092792511 0.311630964279 0.241738080978
 

Here we get the addition idiom being closer to a factor of four
instead of two slower. The .joim idiom is still nearly identical.

mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jargons of Info Tech industry

2005-10-22 Thread noah bedford
On Wed, 12 Oct 2005 21:50:22 GMT
Roedy Green [EMAIL PROTECTED] wrote:

It is almost like providing ladders and setting out cookies and milk
for the burglars.

Fire escapes at christmas.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: KeyboardInterrupt vs extension written in C

2005-10-22 Thread Dieter Maurer
Tamas Nepusz [EMAIL PROTECTED] writes on 20 Oct 2005 15:39:54 -0700:
 The library I'm working on
 is designed for performing calculations on large-scale graphs (~1
 nodes and edges). I want to create a Python interface for that library,
 so what I want to accomplish is that I could just type from igraph
 import * in a Python command line and then access all of the
 functionalities of the igraph library. Now it works, except the fact
 that if, for example, I start computing the diameter of a random graph
 of ~10 nodes and ~20 edges, I can't cancel it, because the
 KeyboardInterrupt is not propagated to the Python toplevel (or it isn't
 even generated until the igraph library routine returns).

Python installs a SIGINT handler that just notes that
such a signal was received. The note is handled during
bytecode execution. This way, Python handles the (dangerous)
asynchronous signal synchronously (which is much safer).
But, it also means that a signal during execution of your C extension
is only handled when it finished.

What you can do in your wrapper code:

   Temporarily install a new handler for SIGINT that
   uses longjmp to quit the C extension execution when
   the signal occurs.

   Note that longjmp is dangerous. Great care is necessary.

   It is likely that SIGINT occurrences will lead to big
   resource leaks (because your C extension will have no
   way to release resources when it gets quit with longjmp).


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


Re: python gc performance in large apps

2005-10-22 Thread Jp Calderone
On Fri, 21 Oct 2005 16:13:09 -0400, Robby Dermody [EMAIL PROTECTED] wrote:

Hey guys (thus begins a book of a post :),

I'm in the process of writing a commercial VoIP call monitoring and
recording application suite in python and pyrex. Basically, this
software sits in a VoIP callcenter-type environment (complete with agent
phones and VoIP servers), sniffs voice data off of the network, and
allows users to listen into calls. It can record calls as well. The
project is about a year and 3 months in the making and lately the
codebase has stabilized enough to where it can be used by some of our
clients. The entire project has about 37,000 lines of python and pyrex
code (along with 1-2K lines of unrelated java code).

 [snip - it leaks memory]

One thing to consider is that the process may be growing in size, not because 
garbage objects are not being freed, but because objects which should be 
garbage are being held onto by application-level code.

gc.objects may be useful for determining if this is the case, and 
gc.get_objects() may be useful for discovering what kinds of objects are piling 
up.  These may give you a hint as to where to look to allow these objects to be 
released, if this is the problem.

Of course, it's also possible one of the libraries you are using is either 
leaking objects in this fashion, or for the extension modules, may just be 
leaking memory.  The above techniques may help you find an object leak, but 
they won't help you find a memory leak.  For this, you might give Valgrind a 
try (use the suppression file in Python CVS to get rid of the spew PyMalloc and 
friends generate).

Also, I can point out two things: Twisted's URL parsing extension leaked some 
memory in 1.3, but has been fixed since 2.0; and Nevow 0.4.1 made it easy to 
write applications that leaked several page objects per request, which has been 
fixed since 0.5.  If you're using either of these older versions, upgrading may 
fix your difficulties.

Hope this helps,

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


Re: KeyboardInterrupt vs extension written in C

2005-10-22 Thread Jp Calderone
On 22 Oct 2005 22:02:46 +0200, Dieter Maurer [EMAIL PROTECTED] wrote:
Tamas Nepusz [EMAIL PROTECTED] writes on 20 Oct 2005 15:39:54 -0700:
 The library I'm working on
 is designed for performing calculations on large-scale graphs (~1
 nodes and edges). I want to create a Python interface for that library,
 so what I want to accomplish is that I could just type from igraph
 import * in a Python command line and then access all of the
 functionalities of the igraph library. Now it works, except the fact
 that if, for example, I start computing the diameter of a random graph
 of ~10 nodes and ~20 edges, I can't cancel it, because the
 KeyboardInterrupt is not propagated to the Python toplevel (or it isn't
 even generated until the igraph library routine returns).

Python installs a SIGINT handler that just notes that
such a signal was received. The note is handled during
bytecode execution. This way, Python handles the (dangerous)
asynchronous signal synchronously (which is much safer).
But, it also means that a signal during execution of your C extension
is only handled when it finished.

What you can do in your wrapper code:

   Temporarily install a new handler for SIGINT that
   uses longjmp to quit the C extension execution when
   the signal occurs.

   Note that longjmp is dangerous. Great care is necessary.

   It is likely that SIGINT occurrences will lead to big
   resource leaks (because your C extension will have no
   way to release resources when it gets quit with longjmp).


Note that swapcontext() is probably preferable to longjmp() in almost all 
circumstances.  In cases where it isn't, siglongjmp() definitely is.

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


High Order Messages in Python

2005-10-22 Thread [EMAIL PROTECTED]
I'm reading about high order messages in Ruby by Nat Pryce, and
thinking if it could be  util and if so, if it could be done in Python.
Someone already tried?

References:
http://lambda-the-ultimate.org/node/view/1047
http://nat.truemesh.com/archives/000535.html
http://nat.truemesh.com/archives/000537.html

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


Re: Re: PID and/or handle assistance. . .?

2005-10-22 Thread Michael Williams
On Oct 22, 2005, at 1:16 PM, [EMAIL PROTECTED] wrote:Michael Williams wrote: Hi All, Can anyone explain how to both spawn processes from PYTHON and  acquire their process IDs or a handle to them for use later?  I'd  also like to acquire the stdout of each spawned process.  Google dead today? Well, check out the modules subprocess, popen2 and os.  Regards,  Diez No, Google certainly isn't dead.  I simply figured I'd ask those in the know instead of mindlessly meandering the web.  Anyway, I've checked out the OS module and although I can find examples of say .fork, and .popen, they aren't extremely informative or straightforward.  Any other ideas/examples?Regards-- 
http://mail.python.org/mailman/listinfo/python-list

Question about inheritance...

2005-10-22 Thread KraftDiner
I have a base class called Shape
And then classes like Circle, Square, Triangle etc, that inherit from
Shape:

My quesiton is can a method of the Shape class call a method in Circle,
or Square etc...?

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


Re: best way to replace first word in string?

2005-10-22 Thread Ron Adam
Steven D'Aprano wrote:

 def replace_word(source, newword):
 Replace the first word of source with newword.
 return newword +   + .join(source.split(None, 1)[1:])
 
 import time
 def test():
 t = time.time()
 for i in range(1):
 s = replace_word(aa to become, /aa/)
 print ((time.time() - t)/1), s
 
 py test()
 3.6199092865e-06 s
 
 
 Is that fast enough for you?


I agree in most cases it's premature optimization.  But little tests 
like this do help in learning to write good performing code in general.

Don't forget a string can be sliced.  In this case testing before you 
leap is a win.   ;-)


import time
def test(func, n):
 t = time.time()
 s = ''
 for i in range(n):
 s = func(aa to become, /aa/)
 tfunc = t-time.time()
 print func.__name__,':', (tfunc/n), s
 print s

def replace_word1(source, newword):
 Replace the first word of source with newword.
 return newword +   + .join(source.split(None, 1)[1:])

def replace_word2(source, newword):
 Replace the first word of source with newword.
 if ' ' in source:
 return newword + source[source.index(' '):]
 return newword

test(replace_word1, 1)
test(replace_word2, 1)


===
replace_word1 : -3.09998989105e-006 s
/aa/ to become
replace_word2 : -1.6324249e-006 s
/aa/ to become

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


Re: best way to replace first word in string?

2005-10-22 Thread [EMAIL PROTECTED]
The RE way, was much slower
I used the spilt, it was better
I tought because there was no need to take it to the memory again, but
it just my thougth

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


Re: Question about inheritance...

2005-10-22 Thread Oliver Andrich
Hi,

22 Oct 2005 14:40:09 -0700, KraftDiner [EMAIL PROTECTED]:
 I have a base class called Shape
 And then classes like Circle, Square, Triangle etc, that inherit from
 Shape:

 My quesiton is can a method of the Shape class call a method in Circle,
 or Square etc...?

even there would exist a way to accomplish that, I would suggest to
rethink your class hierachy. Such requirements can show serious design
problems.

Best regards,
Oliver

--
Oliver Andrich [EMAIL PROTECTED] --- http://roughbook.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about inheritance...

2005-10-22 Thread Mike Meyer
KraftDiner [EMAIL PROTECTED] writes:

 I have a base class called Shape
 And then classes like Circle, Square, Triangle etc, that inherit from
 Shape:

 My quesiton is can a method of the Shape class call a method in Circle,
 or Square etc...?

Yup:

 class Shape(object):
...  def commented_draw(self):
...   print Drawing, self.__class__.__name__
...   self.draw()
... 
 class Circle(Shape):
...  def draw(self):
...   print Drawing a Circle
... 
 c = Circle()
 c.commented_draw()
Drawing Circle
Drawing a Circle
 

Or maybe you meant invoking them directly, which a method in Shape
would do by calling Circle.draw(self). The latter is ugly - you should
use self.draw() to invoke the draw routine that's correct for self.

mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: High Order Messages in Python

2005-10-22 Thread Jp Calderone
On 22 Oct 2005 14:12:16 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
I'm reading about high order messages in Ruby by Nat Pryce, and
thinking if it could be  util and if so, if it could be done in Python.
Someone already tried?

Here's an example of the idea, in Python:

def messageA():
print 'Message A received!'

def messageB(otherMessage):
print 'Message B received!  Sending some other message.'
otherMessage()

messageB(messageA)

Since this is a basic feature of Python, we usually don't call them messages.  
Instead, functions or sometimes methods.

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


Re: High Order Messages in Python

2005-10-22 Thread [EMAIL PROTECTED]
Hum... I thnk you dont get the ideia: I'm not talking abou High Order
Functions.
What ho call High Order Methods is some like connecting some
'generic' methods created to do things like this:
claimants.where.retired?.do.receive_benefit 50
The 2nd and 3rd links that in the first post is the most relevant to
undestand the concept. Read this too:
http://www.metaobject.com/papers/Higher_Order_Messaging_OOPSLA_2005.pdf

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


Re: Question about inheritance...

2005-10-22 Thread Ron Adam
KraftDiner wrote:

 I have a base class called Shape
 And then classes like Circle, Square, Triangle etc, that inherit from
 Shape:
 
 My quesiton is can a method of the Shape class call a method in Circle,
 or Square etc...?


This looks familiar. :-)

Yes, it can if it has references to them.

Could you explain a little better what you are doing.

Since I'm working on the same (or similar) thing maybe we can share our 
results, (or efforts).

Cheers,
Ron


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


System tray Icon

2005-10-22 Thread Mike Pippin
How would I have an app run with just a system tray Icon??? any help would be greatly appreciated. I have no clue where to start.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: High Order Messages in Python

2005-10-22 Thread Jp Calderone
On 22 Oct 2005 15:11:39 -0700, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
Hum... I thnk you dont get the ideia: I'm not talking abou High Order
Functions.
What ho call High Order Methods is some like connecting some
'generic' methods created to do things like this:
claimants.where.retired?.do.receive_benefit 50
The 2nd and 3rd links that in the first post is the most relevant to
undestand the concept. Read this too:
http://www.metaobject.com/papers/Higher_Order_Messaging_OOPSLA_2005.pdf

These are just more involved applications of the same idea.  They're easily 
implemented in Python, using primitives such as HOF, if one desires.

However, I don't see why one would want to write the above mish-mash, rather 
than:

for cl in claimaints:
if cl.retired():
cl.receive_benefit(50)

Or:

[cl.receive_benefit(50) for cl in claimaints if cl.retired())

Or:

map(
ClaimaintType.receive_benefit,
filter(
ClaimaintType.retired,
claimaints),
itertools.repeat(50))

Or:

claimaintGroup.disburse()

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


Re: High Order Messages in Python

2005-10-22 Thread Sam Pointon
This can be suitably applied to Python with the use of Higher Order
Functions, though. It's not quite the Ruby version because Python
allows you to use functions as first-class objects, complicating the
All-You-Can-Do-Is-Pass-A-Message philosophy. This is my 5-minute
implementation:


class HigherOrderList(list):

def do(self, func):
return HigherOrderList(each(self, func))

def where(self, pred):
return HigherOrderList(mass_test(self, pred))

def mass_test(iterable, pred):
for item in iterable:
if pred(item):
yield item

def each(iterable, method):
for item in iterable:
yield method(item)

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


Re: Microsoft Hatred FAQ

2005-10-22 Thread Tim Tyler
Mike Meyer [EMAIL PROTECTED] wrote or quoted:

 Wrong. The only obligation Microsoft has is to their shareholders.
 That obligation has nothing to do with computing - it's to make a
 profit. It's MS's habit of doing things in pursuit of profit that,
 while short of force, are borderline fraud, and are illegal, immoral,
 unethical, bad for their business partners, bad for their customers,
 bad for the industry and bad for society that causes people to
 characterize them as evil.

Microsoft still comes in at number 2 - on:

http://dmoz.org/Society/Issues/Business/Allegedly_Unethical_Firms/

Few companies are more despised than Microsoft.
-- 
__
 |im |yler  http://timtyler.org/  [EMAIL PROTECTED]  Remove lock to reply.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft Hatred FAQ

2005-10-22 Thread David Schwartz

Roedy Green [EMAIL PROTECTED] wrote in 
message news:[EMAIL PROTECTED]

 On Fri, 21 Oct 2005 21:47:27 -0700, David Schwartz
 [EMAIL PROTECTED] wrote or quoted :

 There is no way Microsoft could have expected the
market to be defined in this way and no way to argue that Microsoft had 
any
reason to believe their conduct was illegal.

 If what they did to me in the 90s was not illegal it damn well should
 have been.

If the deal didn't give you more than it cost you, all you had to do was 
say 'no'. I understand the frustration at being forced to pay for something 
what it is worth.

DS


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


Re: Microsoft Hatred FAQ

2005-10-22 Thread David Schwartz

Steven D'Aprano [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 On Fri, 21 Oct 2005 21:47:27 -0700, David Schwartz wrote:

 That's basic economics. Something which can be allowed or ignored or 
 even
 encouraged when done by small businesses in a competitive market can
 easily become harmful and bad for the economy when done by a monopolist 
 or
 duopolist in an uncompetitive market.

 Microsoft goal is and should be their own success, not the success of
 the economy or the market in general.

 Neither I, nor you, nor the government of any nation, should care a
 monkey's toss specifically for Microsoft's success. Microsoft is one
 special interest, out of a potentially unbounded number of possible
 players in the economy of a country and the world.

No, not at all. It is the gravest act of self-contradiction to maintain 
that one should be allowed to pursue one's own interest while denying that 
same right to others.

 Unless you or I are specifically shareholders in Microsoft, we should not
 care about their specific success; and the government should be entirely
 agnostic about who are the winners and losers in an economy.

We should certainly care that Microsoft be allowed to pursue their own 
success. The government should be agnostic about who the winners and losers 
are, but must respect each entity's right to attempt to be that winner.

 The
 government's role should be to ensure a level playing field, and minimum
 levels of health, safety and environmental standards. There is no place
 for government giving special-interests like Microsoft favours.

The problem is, people complain when the playing field is in fact level. 
For example, Microsoft's exclusionary Windows agreements didn't ask for 
more than Windows was worth (or nobody would have agreed to them). Yet they 
are considered examples of the playing field not being level.

 Society regulates where and how we park our cars: for instance, none of us
 are allowed to park our car in the middle of busy road. and if we try, our
 car is likely to be impounded. This is not because there is anything in
 and of itself *wrong* with parking at such-and-such a place, but because
 of the effect it has on others.

Umm, no. It's because the government owns the roads and operates them 
for the benefit of all. This analogy applies *only* to government property.

 A sensible government cares for smooth
 flowing traffic on the roads, with the minimum of delays and the maximum
 flow practical.

You could replace government with road owner and the analogy would 
then be correct. Governments don't give a damn if traffic flows smoothly on 
private roads.

 Perhaps Walmart or Safeway might find it convenient to
 park their trucks on public roads for any number of reasons. Too bad for
 them: the benefit to them does not outweigh the loss to everyone else,
 even if they don't specifically block access to their competitors.

And this is what any road owner would do.

 Microsoft's behaviour over-all has been just as anti-social,
 anti-competitive and harmful to the over-all running of the economy as a
 hypothetical Walmart or Safeway that regularly parked their trucks in the
 middle of the main road for a few hours while they unloaded.

The problem is, the government does not own the economy. So it does not 
get to manage it the way it gets to manage the roads it in fact owns.

 Maybe, just maybe, if Mom  Pop's Corner Store tried it once or twice, we
 could afford to turn a blind eye, especially if the disruption caused by
 towing their delivery van was greater than the disruption caused by their
 double-parking. Thousands of people break the law by double-parking for a
 few minutes, and society doesn't collapse. But something that we can
 afford to ignore when done by MP's Corner Store becomes a serious problem
 if done by somebody with the economic power of Walmart, with their
 thousands of deliveries by 18-wheelers every day across the country.

Again, the analogy fails. You are comparing the government's right to 
manage its own property with the government's right to interfere with 
other people's right to manage their property.

 Microsoft's status of a monopolist
 is only meaningful if you define the market as desktop operating systems
 for 32-bit x86 computers.

 That is *precisely* the market we're talking about. Not any item that
 runs off electricity, not orange juice, not pork bellies, not all
 computing devices, but desktop PCs. What did you think the Justice
 Department's investigation was about? Motor vehicles?

I thought it was about operating systems, actually. And I thought that 
both OSX and Linux competed with it.

 There is no way Microsoft could have expected the
 market to be defined in this way and no way to argue that Microsoft had 
 any
 reason to believe their conduct was illegal.

 Microsoft have lawyers. Microsoft destroyed emails and at least one senior
 manager perjured himself in 

Re: python gc performance in large apps

2005-10-22 Thread Neal Norwitz
Jp Calderone wrote:
 On Fri, 21 Oct 2005 16:13:09 -0400, Robby Dermody [EMAIL PROTECTED] wrote:
 
  [snip - it leaks memory]

 One thing to consider is that the process may be growing in size, not because 
 garbage objects are not being freed, but because objects which should be 
 garbage are being held onto by application-level code.

This is a big problem with Java too.  It's also likely to be a large
source of the memory growth here given that there isn't much cylcic
garbage.  I'm assuming that memory leaks in the python core are going
to be a small percentage of the total.  (Probably also true even if
there are memory leaks in Twisted, etc)  It's so easy to keep data
around you don't realize.

I don't have any particular insight into this problem.  I think Zope
servers can run a long without similar issues, so I think (certainly
hope) it's not endemic to the Python core.  I don't recall any
significant memory leaks fixed between 2.3 and current CVS.  But it
would be interesting to try your app on 2.4 at least to see if it
works.  CVS would also be interesting.

You might want to consider building your own python configuring
--with-pydebug.  This will cause your program to run slower and consume
more memory, but it has additional information available to help find
reference leaks.

Definitely also run under valgrind if possible.  Given the size, I
don't know if electric fence or dbmalloc are realistic options.

Feel free to mail me if you need help with valgrind etc.  I'm very
curious what the root cause of your problem is.  It's possible you are
exercising code in python that isn't commonly used and so we haven't
found a problem yet.  Also consider looking into the issues of the
third party libraries.  Jp mentioned some problems with Twisted stuff.

It would be good if you could provide small test cases that create the
problems you have encountered.

n

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


Re: High Order Messages in Python

2005-10-22 Thread Mike Meyer
[EMAIL PROTECTED] [EMAIL PROTECTED] writes:

 I'm reading about high order messages in Ruby by Nat Pryce, and
 thinking if it could be  util and if so, if it could be done in Python.
 Someone already tried?

Yes, I'm pretty sure it could be done in Python. All it really needs
is the ability to catch references to undefined attributes, which
Python has. You make the HOM of your collection class return an object
with a reference to self, and the __getattr__ method of that classs
then invokes getattr on each object in the referenced collection
instance for the undefined method, manipulating the result as
appropriate for that HOM, and returning a new list.

But this really isn't a very good fit for Python. This is really a
feature for more aggressively OO languages. To make the examples HOMs
described really useful, you want to add them to some base class for
collections. But that base class doesn't exist in Python - Python just
isn't that OO.

You could add various HOMs to lists, tuples, generators and iterators
- but then anyone who wanted to create a new sequence class would have
to add all of the HOMs that their clients might want to use. The
pythonic way would be to add a function that works with all the
various sequence types - which would then automatically work with any
user-defined classes that quacked like a sequence. It's not very OO -
but it is pythonic. In fact, Python already has functions that capture
the functionality of the example HOMs in the links you posted: where
and unless are handled by filter. in_order_of and in_reverse_order_of
are handled by sorted. do is is handled by map. Of course, recent
versions of python provide list comprehensions as preferable to some
of these functions.

That said, HOM's are a *very* powerful mechanism. The examples - and
my discussion of them - cover just one very broad use case. There may
be others where they are a better fit with Python. Having examples of
how to do these kinds of things around is probably worthwhile.

mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs Ruby

2005-10-22 Thread Steven D'Aprano
On Fri, 21 Oct 2005 13:03:29 +0100, Alex Stapleton wrote:

 
 On 21 Oct 2005, at 09:31, Harald Armin Massa wrote:
 
 Casey,



 I have heard, but have not been able to verify that if a program is
 about
 10,000 lines in C++
 it is about
 5,000 lines in Java
 and it is about
 3,000 lines in Python (Ruby to?)

I suspect it is considerably less than that, although it depends on the
specific code being written.


 BTW: it is normally only 50 lines in Perl. Not that you could read it,
 though

 Harald


 Perl is more like a CISC CPU. There are a million different commands.
 Python is more RISC like.
 Line count comparisons = pointless.


Not so.

Every line = more labour for the developer = more cost and time.
Every line = more places for bugs to exist = more cost and time.

I find it sometimes helps to imagine extreme cases. Suppose somebody comes
to you and says Hi, I want you to develop a web scrapping application to
run on my custom hardware. You look at the project specifications and
realise that the hardware has no OS, no TCP/IP, no file manager, no
compiler. So you have to quote the potential customer on writing all these
layers of software, potentially tens of millions of lines of code.
Even porting an existing OS to the new hardware is not an insignificant
job. Think how much time and money it would take.

On the other extreme, the client comes to you and asks the same thing,
except the hardware is a stock-standard Linux-based PC. Your development
environment already contains an operating system, a file manager,
TCP/IP, compilers, frameworks... and wget. The work you need to do is
potentially as little as writing down the command man wget on a slip of
paper and pushing it across the table to your customer.

As programming languages go, C is closer to the first extreme, C++ a
little further away, Java further away still, because Java provides
more capabilities already built-in that the C programmer has to
create from scratch. For many tasks, Python provides even more
capabilities, in a language that demands less syntax scaffolding to make
things happen. Every line of code you don't have to write not only is a
bug that just can't happen, but it also saves time and labour.


-- 
Steven.

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


Re: best way to replace first word in string?

2005-10-22 Thread William Park
Chris F.A. Johnson [EMAIL PROTECTED] wrote:
 On 2005-10-22, William Park wrote:
  [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
  I am looking for the best and efficient way to replace the first word
  in a str, like this:
  aa to become - /aa/ to become
  I know I can use spilt and than join them
  but I can also use regular expressions
  and I sure there is a lot ways, but I need realy efficient one
 
  I doubt you'll find faster than Sed.
 
On the contrary; to change a string, almost anything will be faster
than sed (except another external program).
 
If you are in a POSIX shell, parameter expansion will be a lot
faster.
 
In a python program, one of the solutions already posted will be
much faster.

Care to put a wager on your claim?

-- 
William Park [EMAIL PROTECTED], Toronto, Canada
ThinFlash: Linux thin-client on USB key (flash) drive
   http://home.eol.ca/~parkw/thinflash.html
BashDiff: Super Bash shell
  http://freshmeat.net/projects/bashdiff/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Binding a variable?

2005-10-22 Thread Steven D'Aprano
On Fri, 21 Oct 2005 13:33:18 -0400, Mike Meyer wrote:

 Paul Dale [EMAIL PROTECTED] writes:
 
 Hi everyone,

 Is it possible to bind a list member or variable to a variable such that

 temp = 5

 list = [ temp ]

Don't use the names of built-in functions as variables.

 temp == 6

 list

 would show

 list = [ 6 ]
 
 No. You need to either put a mutable in the list, or subclass list so
 that indexing gets the value, looks it up in the appropriate
 namespace, and returns that value.


Or something even conceptually simpler than having to muck about with
looking up different namespaces:

class Data:
def __init__(self, obj):
self.value = obj
def __str__(self):
return self.value

temp = Data(5)
L = [temp]
print L

will give 5.

temp.value = 6
print L

will now give 6.


-- 
Steven.

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


Re: Python cgi

2005-10-22 Thread jbrewer
I added enctype=multipart/form-data  to the form tag, and that
seemed to solve it.  Thanks.

Jeremy

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


Re: Microsoft Hatred FAQ

2005-10-22 Thread Mike Meyer
David Schwartz [EMAIL PROTECTED] writes:
 Steven D'Aprano [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 On Fri, 21 Oct 2005 21:47:27 -0700, David Schwartz wrote:
 That's basic economics. Something which can be allowed or ignored or 
 even
 encouraged when done by small businesses in a competitive market can
 easily become harmful and bad for the economy when done by a monopolist 
 or
 duopolist in an uncompetitive market.
 Microsoft goal is and should be their own success, not the success of
 the economy or the market in general.
 Neither I, nor you, nor the government of any nation, should care a
 monkey's toss specifically for Microsoft's success. Microsoft is one
 special interest, out of a potentially unbounded number of possible
 players in the economy of a country and the world.
 No, not at all. It is the gravest act of self-contradiction to maintain 
 that one should be allowed to pursue one's own interest while denying that 
 same right to others.

Not at all. No one is denying anyones right to purssue their own
interest. What's being denied is the right to use illegal means to do
so. If MS restricted themselves to legal means, no one would have a
problem with them.

 Unless you or I are specifically shareholders in Microsoft, we should not
 care about their specific success; and the government should be entirely
 agnostic about who are the winners and losers in an economy.
 We should certainly care that Microsoft be allowed to pursue their own 
 success. The government should be agnostic about who the winners and losers 
 are, but must respect each entity's right to attempt to be that winner.

Nice thought. Unfortunately, the government doesn't work that
way. They believe that a practical monopoly is a bad thing, and limit
the things such a company can do, and have been known to disassemble
companies they believe are harming the economy in general.

 The
 government's role should be to ensure a level playing field, and minimum
 levels of health, safety and environmental standards. There is no place
 for government giving special-interests like Microsoft favours.
 The problem is, people complain when the playing field is in fact level. 
 For example, Microsoft's exclusionary Windows agreements didn't ask for 
 more than Windows was worth (or nobody would have agreed to them). Yet they 
 are considered examples of the playing field not being level.

No, they didn't ask for more than Windows were worth. They tilted the
playing field against MS competitors by causing consumers to pay MS
money for products they didn't receive. In most countries, taking
money from unwilling victims without giving them anything in exchange
is called theft.

 Microsoft's behaviour over-all has been just as anti-social,
 anti-competitive and harmful to the over-all running of the economy as a
 hypothetical Walmart or Safeway that regularly parked their trucks in the
 middle of the main road for a few hours while they unloaded.
 The problem is, the government does not own the economy. So it does not 
 get to manage it the way it gets to manage the roads it in fact owns.

Sorry, but you're wrong. The government *does* own the econnomy. Who
do you think originally created all the money that is flowing through
it? The government charges you for the privilege of participating in
their economy - it's called income tax. 2000 years ago Christ knew
who owned the economy, and said Render unto Ceaser that which is
Ceasers.

 Maybe, just maybe, if Mom  Pop's Corner Store tried it once or twice, we
 could afford to turn a blind eye, especially if the disruption caused by
 towing their delivery van was greater than the disruption caused by their
 double-parking. Thousands of people break the law by double-parking for a
 few minutes, and society doesn't collapse. But something that we can
 afford to ignore when done by MP's Corner Store becomes a serious problem
 if done by somebody with the economic power of Walmart, with their
 thousands of deliveries by 18-wheelers every day across the country.
 Again, the analogy fails. You are comparing the government's right to 
 manage its own property with the government's right to interfere with 
 other people's right to manage their property.

Sorry, but nobody but the government actually owns property. In most
places, you can't make non-trivial changes to your property without
permission from the government. They even charge you rent on your
property, only they call it property tax.

 Microsoft's status of a monopolist
 is only meaningful if you define the market as desktop operating systems
 for 32-bit x86 computers.
 That is *precisely* the market we're talking about. Not any item that
 runs off electricity, not orange juice, not pork bellies, not all
 computing devices, but desktop PCs. What did you think the Justice
 Department's investigation was about? Motor vehicles?
 I thought it was about operating systems, actually. And I thought that 
 

Re: Python vs Ruby

2005-10-22 Thread Mike Meyer
Steven D'Aprano [EMAIL PROTECTED] writes:
 On Fri, 21 Oct 2005 13:03:29 +0100, Alex Stapleton wrote:
 Perl is more like a CISC CPU. There are a million different commands.
 Python is more RISC like.
 Line count comparisons = pointless.

 Not so.

 Every line = more labour for the developer = more cost and time.
 Every line = more places for bugs to exist = more cost and time.

There were studies done in the 70s that showed that programmers
produced the same number of debugged lines of code a day no matter
what language they used. So a language that lets you build the same
program with fewer lines of code will let you build the program in
less time.

 I find it sometimes helps to imagine extreme cases. Suppose somebody comes
 to you and says Hi, I want you to develop a web scrapping application to
 run on my custom hardware. You look at the project specifications and
 realise that the hardware has no OS, no TCP/IP, no file manager, no
 compiler. So you have to quote the potential customer on writing all these
 layers of software, potentially tens of millions of lines of code.
 Even porting an existing OS to the new hardware is not an insignificant
 job. Think how much time and money it would take.

Then factor in the profits to be reaped from selling the ported
OS/compilers :-).

mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Binding a variable?

2005-10-22 Thread Mike Meyer
Steven D'Aprano [EMAIL PROTECTED] writes:

 On Fri, 21 Oct 2005 13:33:18 -0400, Mike Meyer wrote:

 Paul Dale [EMAIL PROTECTED] writes:
 
 Hi everyone,

 Is it possible to bind a list member or variable to a variable such that

 temp = 5

 list = [ temp ]

 Don't use the names of built-in functions as variables.

 temp == 6

 list

 would show

 list = [ 6 ]
 
 No. You need to either put a mutable in the list, or subclass list so
 that indexing gets the value, looks it up in the appropriate
 namespace, and returns that value.

 Or something even conceptually simpler than having to muck about with
 looking up different namespaces:
[elided]

Um, that's the *first* solution I proposed: putting a mutable on the
list.

mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best way to replace first word in string?

2005-10-22 Thread Chris F.A. Johnson
On 2005-10-22, William Park wrote:
 Chris F.A. Johnson [EMAIL PROTECTED] wrote:
 On 2005-10-22, William Park wrote:
  [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
  I am looking for the best and efficient way to replace the first word
  in a str, like this:
  aa to become - /aa/ to become
  I know I can use spilt and than join them
  but I can also use regular expressions
  and I sure there is a lot ways, but I need realy efficient one
 
  I doubt you'll find faster than Sed.
 
On the contrary; to change a string, almost anything will be faster
than sed (except another external program).
 
If you are in a POSIX shell, parameter expansion will be a lot
faster.
 
In a python program, one of the solutions already posted will be
much faster.

 Care to put a wager on your claim?

   In a shell, certainly.

   If one of the python solutions is not faster than sed (e.g.,
   os.system(sed .)) I'll forget all about using python.

-- 
Chris F.A. Johnson http://cfaj.freeshell.org
==
Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress
http://www.torfree.net/~chris/books/cfaj/ssr.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best way to replace first word in string?

2005-10-22 Thread Steven D'Aprano
On Sat, 22 Oct 2005 21:41:58 +, Ron Adam wrote:

 Don't forget a string can be sliced.  In this case testing before you 
 leap is a win.   ;-)

Not much of a win: only a factor of two, and unlikely to hold in all
cases. Imagine trying it on *really long* strings with the first space
close to the far end: the split-and-join algorithm has to walk the string
once, while your test-then-index algorithm has to walk it twice.

So for a mere factor of two benefit on short strings, I'd vote for the
less complex split-and-join version, although it is just a matter of
personal preference.

-- 
Steven.

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


Re: Question about inheritance...

2005-10-22 Thread KraftDiner
Well here is a rough sketch of my code...
This is giving my two problems.

1) TypeError: super() argument 1 must be type, not classobj
2) I want to be sure the the draw code calls the inherited classes
outline and not its own...

class Shape:
def __init__(self):
pass
def render(self):
print self.__class___
self.outline()
def outline(self):
pass

class Rect(Shape):
def __init__(self):
super(self.__class__, self).__init__()
def render(self):
super(self.__class__, self).draw()
def outline(self):
print 'outline' + self.__class__

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


Re: Microsoft Hatred FAQ

2005-10-22 Thread Roedy Green
On Sat, 22 Oct 2005 16:10:24 -0700, David Schwartz
[EMAIL PROTECTED] wrote or quoted :

If the deal didn't give you more than it cost you, all you had to do was 
say 'no'. I understand the frustration at being forced to pay for something 
what it is worth.

The choice was go along with MS arm twisting or go out of business.

I call that extortion.
-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft Hatred FAQ

2005-10-22 Thread David Schwartz

Mike Meyer [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 Neither I, nor you, nor the government of any nation, should care a
 monkey's toss specifically for Microsoft's success. Microsoft is one
 special interest, out of a potentially unbounded number of possible
 players in the economy of a country and the world.

 No, not at all. It is the gravest act of self-contradiction to 
 maintain
 that one should be allowed to pursue one's own interest while denying 
 that
 same right to others.

 Not at all. No one is denying anyones right to purssue their own
 interest. What's being denied is the right to use illegal means to do
 so. If MS restricted themselves to legal means, no one would have a
 problem with them.

The conclusion that the means were illegal is predicated on the 
definition of the relevent market as desktop operating systems for 32-bit 
x86 computers. Conduct is not illegal unless some law puts people on 
adequate notice that their conduct is illegal. What law put Microsoft on 
notice that the relevent market would be defined in the bizarre and almost 
nonsensical way?

 Unless you or I are specifically shareholders in Microsoft, we should 
 not
 care about their specific success; and the government should be entirely
 agnostic about who are the winners and losers in an economy.

 We should certainly care that Microsoft be allowed to pursue their 
 own
 success. The government should be agnostic about who the winners and 
 losers
 are, but must respect each entity's right to attempt to be that winner.

 Nice thought. Unfortunately, the government doesn't work that
 way. They believe that a practical monopoly is a bad thing, and limit
 the things such a company can do, and have been known to disassemble
 companies they believe are harming the economy in general.

In other words, they believe the rights of Microsoft to do what they 
please with what is theirs is subservient to some general obligation to help 
the economy as a whole. I am saying that Microsoft has no obligaiton to the 
economy as a whole but instead has an obligation to its stockholders. It 
would be the gravest dereliction of that obligation for Microsoft to 
sacrifice itself for some general benefit.

 The
 government's role should be to ensure a level playing field, and minimum
 levels of health, safety and environmental standards. There is no place
 for government giving special-interests like Microsoft favours.

 The problem is, people complain when the playing field is in fact 
 level.
 For example, Microsoft's exclusionary Windows agreements didn't ask for
 more than Windows was worth (or nobody would have agreed to them). Yet 
 they
 are considered examples of the playing field not being level.

 No, they didn't ask for more than Windows were worth. They tilted the
 playing field against MS competitors by causing consumers to pay MS
 money for products they didn't receive. In most countries, taking
 money from unwilling victims without giving them anything in exchange
 is called theft.

It is not theft if you can simply say no to the deal and all that 
happens is that you don't get the product. Your argument is preposterous. If 
you accept arguments that equate guns with arguments, the next step is that 
using a gun is a rational response to an argument one doesn't like. Oh wait, 
you're already there.

 Microsoft's behaviour over-all has been just as anti-social,
 anti-competitive and harmful to the over-all running of the economy as a
 hypothetical Walmart or Safeway that regularly parked their trucks in 
 the
 middle of the main road for a few hours while they unloaded.

 The problem is, the government does not own the economy. So it does 
 not
 get to manage it the way it gets to manage the roads it in fact owns.

 Sorry, but you're wrong. The government *does* own the econnomy.

If you believe that, then there is no reaching you with reason.

 Who
 do you think originally created all the money that is flowing through
 it?

The government created a medium of exchange, but that is not the same as 
saying it created the wealth that money represents. The government created 
the money simply as a stand in for the wealth that was created by others.

 The government charges you for the privilege of participating in
 their economy - it's called income tax. 2000 years ago Christ knew
 who owned the economy, and said Render unto Ceaser that which is
 Ceasers.

The government charges you, notionally, for the services it provides. It 
is somewhat silly to phrase as this as charging you for the privilege of 
participating in *their* economy. I am familiar with just about every theory 
for justifying government power, and I know of none that justifies a claim 
of complete government ownership of the economy other than those that lead 
to Communism or Totalitariansm.

 Maybe, just maybe, if Mom  Pop's Corner Store tried it once or twice, 
 we
 could afford to turn a blind eye, 

Re: Listening for keypress in the background

2005-10-22 Thread Mathias Dahl
Mathias Dahl [EMAIL PROTECTED] writes:

 Peter Hansen [EMAIL PROTECTED] writes:

 How can I make it listen for a certain keypress (say, Windows-key +
 space) in a controlled fashion even when it is not the program having
 focus?
 
 I need to do this running under GNOME in Mandrake GN/Linux 10.

 Search Google for python keylogger.

 Thanks, good idea! The relevant pages I found only link to
 Windows-specific keyloggers though.

 I just got another idea on a solution for my main problem (invoking my
 sleeping app) and that would be to let my window manager execute a
 small invoker program that would communicate with the sleeping
 app. The question is, which is the easiest way to communicate with a
 running Python program? Signals? TCP/IP (not really, right?) Pipes?

I solved it using named pipes (mkfifo, open and read) plus a simple
echo x  pipe to invoke.

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


Re: Microsoft Hatred FAQ

2005-10-22 Thread David Schwartz

Roedy Green [EMAIL PROTECTED] wrote in 
message news:[EMAIL PROTECTED]

 On Sat, 22 Oct 2005 16:10:24 -0700, David Schwartz
 [EMAIL PROTECTED] wrote or quoted :

If the deal didn't give you more than it cost you, all you had to do 
 was
say 'no'. I understand the frustration at being forced to pay for 
something
what it is worth.

 The choice was go along with MS arm twisting or go out of business.

Only because the product they were providing you was so important you 
were unable to do business without it.

 I call that extortion.

Microsoft had something you need so badly that you could not go into 
business without it. So they demanded from you that you pay them what their 
software was actually worth to you. That is not extortion. Everyone who 
sells something tries to get the maximum possible value for it.

(Of course, you could have gone into business selling servers. Or 
Macintoshes. Or another business entirely. It was only to go into the 
business of selling PCs with Windows that you had to deal with Microsoft.)

DS


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


Re: Microsoft Hatred FAQ

2005-10-22 Thread Roedy Green
On Sun, 23 Oct 2005 01:00:31 GMT, Roedy Green
[EMAIL PROTECTED] wrote or quoted :

The choice was go along with MS arm twisting or go out of business.

I call that extortion.

I deeply resent this, because they not only ripped me off, they put me
a in position I felt compelled to become part of their dirty business
scheme.  I am angrier for my own uncleanness than I am at my actual
financial losses.

I despise them for corrupting me. 


-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about inheritance...

2005-10-22 Thread KraftDiner
This is what I've got so far:
class Shape(object):
def __init__(self):
pass
def render(self):
print 'Shape render'
self.outline()
def outline(self):
pass

class Rect(Shape):
def __init__(self):
super(self.__class__, self).__init__()
def render(self):
super(self.__class__, self).render()
def outline(self):
print 'Rect outline'

r = Rect()
r.render()

The output:

Shape render
Rect outline

Cool.. I guess its working..

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


Re: Question about inheritance...

2005-10-22 Thread Alex Martelli
KraftDiner [EMAIL PROTECTED] wrote:

 Well here is a rough sketch of my code...
 This is giving my two problems.
 
 1) TypeError: super() argument 1 must be type, not classobj

Make your classes new-style (have Shape inherit from object) to fix
this.  You're using the legacy (old-style) object model (which remains
for backwards compatibility only).

 2) I want to be sure the the draw code calls the inherited classes
 outline and not its own...

Call anything on self, and you'll use the inherited class.


 class Shape:

change to: class Shape(object):

   def __init__(self):
   pass

remove this method, no need for it.

   def render(self):
   print self.__class___

Use two trailing underscores, NOT three.

   self.outline()
   def outline(self):
   pass

Use as the body raise NotImplementedError to make sure that
Shape.outline never gets accidentally called.

 
 class Rect(Shape):
   def __init__(self):
   super(self.__class__, self).__init__()
   def render(self):
   super(self.__class__, self).draw()

You never defined a method named 'draw', do you mean 'render'?

   def outline(self):
   print 'outline' + self.__class__



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


Re: Microsoft Hatred FAQ

2005-10-22 Thread Steven D'Aprano
On Sat, 22 Oct 2005 16:17:20 -0700, David Schwartz wrote:

 Microsoft goal is and should be their own success, not the success of
 the economy or the market in general.
 
 Neither I, nor you, nor the government of any nation, should care a
 monkey's toss specifically for Microsoft's success. Microsoft is one
 special interest, out of a potentially unbounded number of possible
 players in the economy of a country and the world.
 
 No, not at all. It is the gravest act of self-contradiction to maintain 
 that one should be allowed to pursue one's own interest while denying that 
 same right to others.

This is perhaps the most ignorant thing I've seen written down by somebody
educated for a long, long long time. An individual's self-interest may
very well include theft, murder or rape, to mention just a few examples.

Pursuing one's own self-interest is not and never has been an unrestricted
right. At the point that your self-interest harms others, civilization
steps in and slaps you down. You are not allowed to pursue your own
self-interest by dumping your trash over the fence into your neighbour's
back yard. You are not allowed to pursue your own self-interest by putting
a bullet in the brain of that annoying busker on the sub-way playing
Beatles tunes badly. You are not allowed to pursue your own self-interest
in breaking into your neighbour's home and stealing his property. And
neither are you allowed to pursue your own self-interest by engaging in
predatory and anti-competitive business practices.

Now perhaps you personally would like to live in a society where Steve
Ballmer, pursuing Microsoft's own interests, is allowed to have Google CEO
Eric Schmidt gut-shot and left to bleed to death in the gutter, but I
think the vast majority of people think that behaviour like that should be
discouraged, no matter how much money that would make Microsoft.


 Unless you or I are specifically shareholders in Microsoft, we should
 not care about their specific success; and the government should be
 entirely agnostic about who are the winners and losers in an economy.
 
 We should certainly care that Microsoft be allowed to pursue their
 own
 success. The government should be agnostic about who the winners and
 losers are, but must respect each entity's right to attempt to be that
 winner.

Certainly. Like any other entity, Microsoft is allowed to live it's life
any way it sees fit, so long as it obeys the law. At the point it breaks
the law, then, like any other legal person, Microsoft should be punished,
by fines, prohibitions, seizure of property, and if need be, the death
penalty.

Or would you like to suggest that Microsoft's board of directors should be
allowed carte blache to break any law, commit any deed, so long as it
makes Microsoft money? 


 The
 government's role should be to ensure a level playing field, and
 minimum levels of health, safety and environmental standards. There is
 no place for government giving special-interests like Microsoft
 favours.
 
 The problem is, people complain when the playing field is in fact
 level.
 For example, Microsoft's exclusionary Windows agreements didn't ask
 for more than Windows was worth (or nobody would have agreed to them).
 Yet they are considered examples of the playing field not being level.

Microsoft's exclusively agreements -- no need for scare quotes -- gave
people the choice, sign this agreement or go out of business. As such,
they are as level a playing field as a thug demanding a restaurant pay
insurance to him or lot of flammable goods in your kitchen, terrible if
it were to burn down.

Microsoft's behaviour was merely smoother, wearing an expensive suit, and
written up in lots of legal language, but in effect it was no different:
do what we want, or we'll put you out of business.


 Society regulates where and how we park our cars: for instance, none of
 us are allowed to park our car in the middle of busy road. and if we
 try, our car is likely to be impounded. This is not because there is
 anything in and of itself *wrong* with parking at such-and-such a
 place, but because of the effect it has on others.
 
 Umm, no. It's because the government owns the roads and operates
 them
 for the benefit of all. This analogy applies *only* to government
 property.

Perhaps you should stop and think for a moment about privately owned toll
roads.

You, as a private individual, are not allowed to detonate a small nuclear
warhead, even on your own property. The government prohibits you from
carrying explosives on privately owned airplanes. I didn't notice the Bush
government shrugging their shoulders and saying Hey, the World Trade
Centre is private property, it is none of *our* business what people do to
it a few years back. Perhaps you might say that it was none of the
government's business, if private individuals wish to fly planes into
privately owned buildings, but fortunately no government in the world
agrees with you.


Re: Microsoft Hatred FAQ

2005-10-22 Thread Steven D'Aprano
On Sat, 22 Oct 2005 18:02:44 -0700, David Schwartz wrote:

 I see you are a totalitarianist or perhaps a communist. If you want to 
 live in America and discuss things that are relevent to America, let me 
 know.

In other words, why don't you go back to Russia, you commie pinko
fascist Jew Nazi.

Mike Meyer has got just as much right to live in America as David
Schwartz. Nice to see how quickly Americans' supposed love of freedom
disappears once they are exposed to views that contradict their own.


-- 
Steven.

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


Re: Python vs Ruby

2005-10-22 Thread Alex Martelli
Mike Meyer [EMAIL PROTECTED] wrote:

  Every line = more labour for the developer = more cost and time.
  Every line = more places for bugs to exist = more cost and time.
 
 There were studies done in the 70s that showed that programmers
 produced the same number of debugged lines of code a day no matter
 what language they used. So a language that lets you build the same
 program with fewer lines of code will let you build the program in
 less time.

Of course, these results only apply where the complexity (e.g., number
of operators, for example) in a single line of code is constant.  There
is no complexity advantage to wrapping up code to take fewer LINES, as
such -- e.g., in Python:

for item in sequence: blaap(item)

or

for item in sequence:
blaap(item)

are EXACTLY as easy (or hard) to write, maintain, and document -- it's
totally irrelevant that the number of lines of code has doubled in the
second (more standard) layout of the code!-)

This effect is even more pronounced in languages which allow or
encourage more extreme variation in packing of code over lines; e.g.,
C, where

for(x=0; x23; x++) { a=seq[x]; zap(a); blup(a); flep(a); }

and

for(x=0;
 x23;
 x++)
  { 
a=seq[x]; 
zap(a);
blup(a);
flep(a);
  }

are both commonly used styles -- the order of magnitude difference in
lines of code is totally illusory.


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


Re: Question about inheritance...

2005-10-22 Thread Kent Johnson
KraftDiner wrote:
 This is what I've got so far:
 class Rect(Shape):
   def __init__(self):
   super(self.__class__, self).__init__()

Should be 
  super(Rect, self).__init__()

   def render(self):
   super(self.__class__, self).render()

ditto

In this example it doesn't make any difference but with a deeper inheritance 
hierachy it does. See
http://www.python.org/2.2.3/descrintro.html#cooperation

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


Re: C extension modules in Python

2005-10-22 Thread Alex Martelli
[EMAIL PROTECTED] wrote:

 Hello,
 
 I'vre written an extension module to accelarate some code i've made in
 python with numarray. Then i compiled an linke d it with swig, my
 problem is that when i make the import in my python code it gives me an
 error: ImportError: libnumarray.so: cannot open shared object file: No
 such file or directory
 
 does anyone know why this hapens and how can i solve it?

It seems that the libnumarray.so (which your extension is probably
trying to load) is not in a directory where your system will like
loading it from.  It's hard to say more without knowing about your
system, and the way you've set things up for it in terms of loading of
dynamic libraries (which IS a very system-dependent thing).


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


Re: path

2005-10-22 Thread Shi Mu
what is the differenc ebetween index and find in the module of string?
for both find and index, I got the position of the letter.
-- 
http://mail.python.org/mailman/listinfo/python-list


index and find

2005-10-22 Thread Shi Mu
what is the difference between index and find in the module of string?
for both find and index, I got the position of the letter.

On 10/19/05, Shi Mu [EMAIL PROTECTED] wrote:
 I have installed Python 2.3 and I type help() and then Keywords.
 I get a list of words. And it says that I can enter any of the words
 to get more help.  I enter
 and and I get the following error message:
 Sorry, topic and keyword documentation is not available because the Python
 HTML documentation files could not be found.  If you have installed them,
 please set the environment variable PYTHONDOCS to indicate their location.

 but I have set both the environment variable, with the path to be
 C:\Python23\Doc which includes python23.chm
 Why I still got the above error message?

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


Re: index and find

2005-10-22 Thread Sam Pointon
 s = 'foobar'
 s.find('z')
-1
 s.index('z')

Traceback (most recent call last):
  File pyshell#32, line 1, in -toplevel-
s.index('z')
ValueError: substring not found


Pretty self explanatory.

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


Re: path

2005-10-22 Thread Erik Max Francis
Shi Mu wrote:

 what is the differenc ebetween index and find in the module of string?
 for both find and index, I got the position of the letter.

  import string
  help(string.find)
Help on function find in module string:

find(s, *args)
 find(s, sub [,start [,end]]) - in

 Return the lowest index in s where substring sub is found,
 such that sub is contained within s[start,end].  Optional
 arguments start and end are interpreted as in slice notation.

 Return -1 on failure.

  help(string.index)
Help on function index in module string:

index(s, *args)
 index(s, sub [,start [,end]]) - int

 Like find but raises ValueError when the substring is not found.

-- 
Erik Max Francis  [EMAIL PROTECTED]  http://www.alcyone.com/max/
San Jose, CA, USA  37 20 N 121 53 W  AIM erikmaxfrancis
   I can't remember to forget you.
   -- Leonard Shelby
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft Hatred FAQ

2005-10-22 Thread Roedy Green
On Sun, 23 Oct 2005 11:46:53 +1000, Steven D'Aprano
[EMAIL PROTECTED] wrote or quoted :


Or would you like to suggest that Microsoft's board of directors should be
allowed carte blache to break any law, commit any deed, so long as it
makes Microsoft money? 

Why should the standards of acceptable conduct be any lower for groups
of people (namely corporations) than individuals?

It would be like excusing bad behaviour based on other group
memberships such as churches or gangs.
-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C extension modules in Python

2005-10-22 Thread Robert Kern
[EMAIL PROTECTED] wrote:
 Hello,
 
 I'vre written an extension module to accelarate some code i've made in
 python with numarray. Then i compiled an linke d it with swig, my
 problem is that when i make the import in my python code it gives me an
 error: ImportError: libnumarray.so: cannot open shared object file: No
 such file or directory
 
 does anyone know why this hapens and how can i solve it?

Are you using distutils to compile and link your extension? You should be.

Are you trying to directly link against libnumarray.so (i.e. by passing
the -lnumarray option to the linker)? You shouldn't be.

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die.
  -- Richard Harter

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


Re: best way to replace first word in string?

2005-10-22 Thread Steven D'Aprano
On Sat, 22 Oct 2005 14:54:24 -0400, Mike Meyer wrote:

 The string formatting is two orders of magnitude faster than the
 concatenation. The speed difference becomes even more obvious when you
 increase the number of strings being concatenated:
 
 The test isn't right - the addition test case includes the time to
 convert the number into a char, including taking a modulo.

I wondered if anyone would pick up on that :-)

You are correct, however that only adds a constant amount of time to
the time it takes for each concatenation. That's why I talked about order
of magnitude differences. If you look at the vast increase in time taken
for concatenation when going from 10**5 to 10**6 iterations, that cannot
be blamed on the char conversion.

At least, that's what it looks like to me -- I'm perplexed by the *vast*
increase in speed in your version, far more than I would have predicted
from pulling out the char conversion. I can think of three
possibilities:

(1) Your PC is *hugely* faster than mine;

(2) Your value of x is a lot smaller than I was using (you don't actually
say what x you use); or

(3) You are using a version and/or implementation of Python that has a
different underlying implementation of string concatenation.



 I couldn't resist adding the .join idiom to this test:

[snip code]

 tester(x)
 0.0551731586456 0.0251281261444 0.0264830589294
 tester(x)
 0.0585241317749 0.0239250659943 0.0256059169769
 tester(x)
 0.0544500350952 0.0271301269531 0.0232360363007

 The order of magnitude now falls to a factor of two. The original
 version of the test on my box also showed an order of magnitude
 difference, so this isn't an implementation difference.

[snip]

 tester(x * 10)
 1.22272014618 0.252701997757 0.27273607254
 tester(x * 10)
 1.21779584885 0.255345106125 0.242965936661
 tester(x * 10)
 1.25092792511 0.311630964279 0.241738080978

Looking just at the improved test of string concatenation, I get times
about 0.02 second for n=10**4. For n=10**5, the time blows out to 2
seconds. For 10**6, it explodes through the roof to about 2800 seconds, or
about 45 minutes, and for 10**7 I'm predicting it would take something of
the order of 500 HOURS.

In other words, yes the char conversion adds some time to the process, but
for large numbers of iterations, it gets swamped by the time taken
repeatedly copying chars over and over again.


-- 
Steven.

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


Re: best way to replace first word in string?

2005-10-22 Thread Ron Adam
Steven D'Aprano wrote:

 On Sat, 22 Oct 2005 21:41:58 +, Ron Adam wrote:
 
 
Don't forget a string can be sliced.  In this case testing before you 
leap is a win.   ;-)
 
 
 Not much of a win: only a factor of two, and unlikely to hold in all
 cases. Imagine trying it on *really long* strings with the first space
 close to the far end: the split-and-join algorithm has to walk the string
 once, while your test-then-index algorithm has to walk it twice.
 
 So for a mere factor of two benefit on short strings, I'd vote for the
 less complex split-and-join version, although it is just a matter of
 personal preference.
 

Guess again...  Is this the results below what you were expecting?

Notice the join adds a space to the end if the source string is a single 
word.  But I allowed for that by adding one in the same case for the 
index method.

The big win I was talking about was when no spaces are in the string. 
The index can then just return the replacement.

These are relative percentages of time to each other.  Smaller is better.

Type 1 = no spaces
Type 2 = space at 10% of length
Type 3 = space at 90% of length

Type: Length

Type 1: 10split/join: 317.38%  index: 31.51%
Type 2: 10split/join: 212.02%  index: 47.17%
Type 3: 10split/join: 186.33%  index: 53.67%
Type 1: 100   split/join: 581.75%  index: 17.19%
Type 2: 100   split/join: 306.25%  index: 32.65%
Type 3: 100   split/join: 238.81%  index: 41.87%
Type 1: 1000  split/join: 1909.40%  index: 5.24%
Type 2: 1000  split/join: 892.02%  index: 11.21%
Type 3: 1000  split/join: 515.44%  index: 19.40%
Type 1: 1 split/join: 3390.22%  index: 2.95%
Type 2: 1 split/join: 2263.21%  index: 4.42%
Type 3: 1 split/join: 650.30%  index: 15.38%
Type 1: 10split/join: 3342.08%  index: 2.99%
Type 2: 10split/join: 1175.51%  index: 8.51%
Type 3: 10split/join: 677.77%  index: 14.75%
Type 1: 100   split/join: 3159.27%  index: 3.17%
Type 2: 100   split/join: 867.39%  index: 11.53%
Type 3: 100   split/join: 679.47%  index: 14.72%




import time
def test(func, source):
 t = time.clock()
 n = 600/len(source)
 s = ''
 for i in xrange(n):
 s = func(source, replace)
 tt = time.clock()-t
 return s, tt

def replace_word1(source, newword):
 Replace the first word of source with newword.
 return newword +   +  .join(source.split(None, 1)[1:])

def replace_word2(source, newword):
 Replace the first word of source with newword.
 if ' ' in source:
 return newword + source[source.index(' '):]
 return newword + ' '   # space needed to match join results


def makestrings(n):
 s1 = 'abcdefghij' * (n//10)
 i, j = n//10, n-n//10
 s2 = s1[:i] + ' ' + s1[i:] + 'd.'# space near front
 s3 = s1[:j] + ' ' + s1[j:] + 'd.'# space near end
 return [s1,s2,s3]

for n in [10,100,1000,1,10,100]:
 for sn,s in enumerate(makestrings(n)):
 r1, t1 = test(replace_word1, s)
 r2, t2 = test(replace_word2, s)
 assert r1 == r2
 print Type %i: %-8i  split/join: %.2f%%  index: %.2f%% \
% (sn+1, n, t1/t2*100.0, t2/t1*100.0)









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


ANN: formulaic 0.1

2005-10-22 Thread gsteff
I've been working on a form generation toolkit that integrates well
with FormEncode... its still under heavy development, of course, but
I've seen a lot of discussion of this topic on various mailing lists
over the past few days, and so wanted to get something out.  Release
early and all that.  So you can get it from

https://developer.berlios.de/project/showfiles.php?group_id=4967

There's a README with a tutorial in there, which is also provided as a
friendlier README.html.  It requires FormEncode (I developed with
FormEncode 0.22, but I expect it will work with older versions).
Current features include default values, intelligent detection and
rendering of required fields, extensive facilities for customization
of the output markup, etc.  Mainly, I've tried to make it easy to use.

I'm a Cherrypy guy, and so aimed it at use with that; it should be
perfectly usable with TurboGears too (although its largely orthagonal
to the (problematic) way that TurboGears currently encourages you to
use forms).  Really, its usable with any framework that lets you access
form submissions as a python dict.

For a really quick intro, I've pasted the contents of a sample script
that uses formulaic below, along with the output that script would
produce.

Its nowhere remotely near finished, of course, but hopefully is at a a
point that it can be useful for real world work.  Questions,
suggestions, etc. are extraordinarily welcome.

Greg

example.py
-
#!/usr/bin/python

from formencode import validators
from formencode.api import Invalid

from formulaic import forms
from formulaic import basicwidgets as widgets

form = forms.RequirementsForm()
form.attrs['id'] = 'myform'

form['age'] = widgets.TextInput(validators.Int(), 'Age')
form['age'].attrs = {'size':'4', 'maxlength':'3'}

colors = ['Red', 'Green', 'Blue']
form['favcolor'] = widgets.Select(validators.OneOf(colors), 'Favorite
color', options=colors)

form['pie'] = widgets.CheckboxInput(validators.Bool(), 'I like pie')

inputs = {'age':'ten', 'favcolor':'Green', 'pie':'checked'}

try:
data = form.schema.to_python(inputs)
print data
except Invalid, error:
print form.render(inputs, error.error_dict)

-

output:

form action= method=POST id=myform

label class=requiredAge/label
input type=text name=age value=ten/
span class=errorPlease enter an integer value/span

label class=requiredFavorite color/label
select type=text name=favcolor
option value=RedRed/option
option selected=selected value=GreenGreen/option
option value=BlueBlue/option
/select

labelI like pie/label
input type=text checked=checked name=pie/

input type=submit value=Submit/

/form

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


IDE recommendation please

2005-10-22 Thread microsnot
I'm new to Python but am wondering what IDE Python developers use? I use Mac
OS X 10.4.2. I have PythonIDE which comes with MacPython but I don't think
that has even rudimentary intellisense. Xcode and Eclipse don't seem to
support Python out of the box. Suggestions for plugins for Eclipse would
also be nice.

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


wxpython - passing arg to wx.app OnInit

2005-10-22 Thread Stuart McGraw
I have a wxPython app, conventionally structured
with a Application class derived from wx.App.
My problem is that the app accepts a command
line argument that must be acted upon within the
OnInit() method of the Application class.  How do
I pass it cleanly from main() into app.OnInit()?  In 
the simplified example below, dbfn is the piece of 
info that is in main() that OnInit() needs to use.
Is a global variable is the only way?  :-(

class Application (wx.App):
def OnInit (self):
oper = Operations (dbfn);
frame = Frame (None, -1, Title, oper)
self.SetTopWindow (frame)
return True

def main ():
dbfn = sys.args[1]
app = Application (redirect=0)
app.MainLoop ()

Apologies if the answer is (or should be) obvious... this
is my first time using wxWindows and I am still rather new 
to Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDE recommendation please

2005-10-22 Thread Alex Martelli
microsnot [EMAIL PROTECTED] wrote:

 I'm new to Python but am wondering what IDE Python developers use? I use Mac
 OS X 10.4.2. I have PythonIDE which comes with MacPython but I don't think
 that has even rudimentary intellisense. Xcode and Eclipse don't seem to
 support Python out of the box. Suggestions for plugins for Eclipse would
 also be nice.

On the Mac, I think the XCode integration you get with PyObjC is
probably best.  I know there are plugins for Eclipse but haven't tried
any personally, so it's hard to make suggestions (I'm a dinosaur, and I
prefer to develop with GVim + a command-line tool, such as Python's own
interactive mode...).  I'm not sure if BlackAdder (simplest and fastest
to learn) and WingIDE (probably THE one most powerful Python IDE) work
on the Mac (shame on me, as a Python AND Mac enthusiast, for not having
tried them...), but they're surely worth investigating.  Ditto for
ActiveState's Komodo tool...


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


Re: best way to replace first word in string?

2005-10-22 Thread [EMAIL PROTECTED]
interesting. seems that if ' ' in source: is a highly optimized code
as it is even faster than if str.find(' ') != -1:' when I assume they
end up in the same C loops ?

Ron Adam wrote:
 Guess again...  Is this the results below what you were expecting?

 Notice the join adds a space to the end if the source string is a single
 word.  But I allowed for that by adding one in the same case for the
 index method.

 The big win I was talking about was when no spaces are in the string.
 The index can then just return the replacement.

 These are relative percentages of time to each other.  Smaller is better.

 Type 1 = no spaces
 Type 2 = space at 10% of length
 Type 3 = space at 90% of length

 Type: Length

 Type 1: 10split/join: 317.38%  index: 31.51%
 Type 2: 10split/join: 212.02%  index: 47.17%
 Type 3: 10split/join: 186.33%  index: 53.67%
 Type 1: 100   split/join: 581.75%  index: 17.19%
 Type 2: 100   split/join: 306.25%  index: 32.65%
 Type 3: 100   split/join: 238.81%  index: 41.87%
 Type 1: 1000  split/join: 1909.40%  index: 5.24%
 Type 2: 1000  split/join: 892.02%  index: 11.21%
 Type 3: 1000  split/join: 515.44%  index: 19.40%
 Type 1: 1 split/join: 3390.22%  index: 2.95%
 Type 2: 1 split/join: 2263.21%  index: 4.42%
 Type 3: 1 split/join: 650.30%  index: 15.38%
 Type 1: 10split/join: 3342.08%  index: 2.99%
 Type 2: 10split/join: 1175.51%  index: 8.51%
 Type 3: 10split/join: 677.77%  index: 14.75%
 Type 1: 100   split/join: 3159.27%  index: 3.17%
 Type 2: 100   split/join: 867.39%  index: 11.53%
 Type 3: 100   split/join: 679.47%  index: 14.72%




 import time
 def test(func, source):
  t = time.clock()
  n = 600/len(source)
  s = ''
  for i in xrange(n):
  s = func(source, replace)
  tt = time.clock()-t
  return s, tt

 def replace_word1(source, newword):
  Replace the first word of source with newword.
  return newword +   +  .join(source.split(None, 1)[1:])

 def replace_word2(source, newword):
  Replace the first word of source with newword.
  if ' ' in source:
  return newword + source[source.index(' '):]
  return newword + ' '   # space needed to match join results


 def makestrings(n):
  s1 = 'abcdefghij' * (n//10)
  i, j = n//10, n-n//10
  s2 = s1[:i] + ' ' + s1[i:] + 'd.'# space near front
  s3 = s1[:j] + ' ' + s1[j:] + 'd.'# space near end
  return [s1,s2,s3]

 for n in [10,100,1000,1,10,100]:
  for sn,s in enumerate(makestrings(n)):
  r1, t1 = test(replace_word1, s)
  r2, t2 = test(replace_word2, s)
  assert r1 == r2
  print Type %i: %-8i  split/join: %.2f%%  index: %.2f%% \
 % (sn+1, n, t1/t2*100.0, t2/t1*100.0)

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


Re: Microsoft Hatred FAQ

2005-10-22 Thread Mike Meyer
David Schwartz [EMAIL PROTECTED] writes:
 Mike Meyer [EMAIL PROTECTED] wrote in message 
 news:[EMAIL PROTECTED]
 Neither I, nor you, nor the government of any nation, should care a
 monkey's toss specifically for Microsoft's success. Microsoft is one
 special interest, out of a potentially unbounded number of possible
 players in the economy of a country and the world.
 No, not at all. It is the gravest act of self-contradiction to 
 maintain
 that one should be allowed to pursue one's own interest while denying 
 that
 same right to others.
 Not at all. No one is denying anyones right to purssue their own
 interest. What's being denied is the right to use illegal means to do
 so. If MS restricted themselves to legal means, no one would have a
 problem with them.
 The conclusion that the means were illegal is predicated on the 
 definition of the relevent market as desktop operating systems for 32-bit 
 x86 computers. Conduct is not illegal unless some law puts people on 
 adequate notice that their conduct is illegal. What law put Microsoft on 
 notice that the relevent market would be defined in the bizarre and almost 
 nonsensical way?

Not at all. The conclusion that the means were illegal was because
*they worked*. If MS didn't have monopoly power, the people they were
dealing with would have laughed at them.

 Unless you or I are specifically shareholders in Microsoft, we should 
 not
 care about their specific success; and the government should be entirely
 agnostic about who are the winners and losers in an economy.

 We should certainly care that Microsoft be allowed to pursue their 
 own
 success. The government should be agnostic about who the winners and 
 losers
 are, but must respect each entity's right to attempt to be that winner.
 Nice thought. Unfortunately, the government doesn't work that
 way. They believe that a practical monopoly is a bad thing, and limit
 the things such a company can do, and have been known to disassemble
 companies they believe are harming the economy in general.
 In other words, they believe the rights of Microsoft to do what they 
 please with what is theirs is subservient to some general obligation to help 
 the economy as a whole. I am saying that Microsoft has no obligaiton to the 
 economy as a whole but instead has an obligation to its stockholders. It 
 would be the gravest dereliction of that obligation for Microsoft to 
 sacrifice itself for some general benefit.

You do like straw men, don't you? Nowhere in the what I said does the
word help appear; you pulled it out of thin air, and what you said
in general has *nothing* to do with what you quoted above. The
statements don't contradict each other in any way, and both happen to
be true.

 The
 government's role should be to ensure a level playing field, and minimum
 levels of health, safety and environmental standards. There is no place
 for government giving special-interests like Microsoft favours.

 The problem is, people complain when the playing field is in fact 
 level.
 For example, Microsoft's exclusionary Windows agreements didn't ask for
 more than Windows was worth (or nobody would have agreed to them). Yet 
 they
 are considered examples of the playing field not being level.
 No, they didn't ask for more than Windows were worth. They tilted the
 playing field against MS competitors by causing consumers to pay MS
 money for products they didn't receive. In most countries, taking
 money from unwilling victims without giving them anything in exchange
 is called theft.
 It is not theft if you can simply say no to the deal and all that 
 happens is that you don't get the product. Your argument is preposterous. If 
 you accept arguments that equate guns with arguments, the next step is that 
 using a gun is a rational response to an argument one doesn't like. Oh wait, 
 you're already there.

Yup, we're there - and you brought us there, by referring to federal
judges as criminals pointing guns.

Of course, there are lots more straw men in this argument. I didn't
mention guns at all - you manufactured that from nothing. Theft
doesn't have to involve guns. Hell, it doesn't even have to involve
the knowledge of the victim, which is the case here. Everyone buying a
system from those that MS bullied paid for an MS OS, whether they got
one or not, and wether they knew it or not - and MS got the
money. They didn't even realize they were being robbed, so saying no
was never an option.

 Microsoft's behaviour over-all has been just as anti-social,
 anti-competitive and harmful to the over-all running of the economy as a
 hypothetical Walmart or Safeway that regularly parked their trucks in 
 the
 middle of the main road for a few hours while they unloaded.

 The problem is, the government does not own the economy. So it does 
 not
 get to manage it the way it gets to manage the roads it in fact owns.

 Sorry, but you're wrong. The government *does* own the econnomy.

 If 

Re: Question about inheritance...

2005-10-22 Thread Ron Adam
KraftDiner wrote:

 Well here is a rough sketch of my code...
 This is giving my two problems.
 
 1) TypeError: super() argument 1 must be type, not classobj
 2) I want to be sure the the draw code calls the inherited classes
 outline and not its own...
 
 class Shape:
   def __init__(self):
   pass
   def render(self):
   print self.__class___
   self.outline()
   def outline(self):
   pass
 
 class Rect(Shape):
   def __init__(self):
   super(self.__class__, self).__init__()
   def render(self):
   super(self.__class__, self).draw()
   def outline(self):
   print 'outline' + self.__class__

I think Alex probably answered your question.  I'm still trying to 
figure out how use inheritance effectively myself.


Are you using this as an way to learn Python or do you want to use 
Python to render images?


What I'm trying to do in relation to this is to build a small subset 
of the SVG standard in tkinter. It looks like the SVG standard is going 
to be very popular graphic format on the web, hand held devices, and as 
a general graphics format.

http://www.w3.org/TR/SVG/

Python doesn't have good SVG support built in without importing a third 
party library, and the ones that are available need other libraries, 
etc...  They don't really support using SVG directly in programs.  So 
I'm experimenting with emplimenting some of the SVG functionality in 
Tkinter for drawing icons in dialog box's.  It's an experiment at the 
moment, but I'd like to see it grow into something more.

It doesn't need to be exactly like it, but the closer it is to the way 
the SVG standard works, the better.  That would make it easier to use 
some 'simple' existing SVG images, and easier to create SVG files as 
well, as it closes the gap between the canvas object and the VGA standard.

Anyway, I'm more than willing to get involved in a group to do this if 
anyone is interested and also thinks it may be worth while.

Cheers,
Ron











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


  1   2   >