Do a "Python beginners e-mail list" exist?

2005-07-07 Thread Alessandro Brollo
Far from a professional programmer, I'm simply a
newbie Python user. Two basic questions:

1. I don't want to post banal questions about Python
to main Python list. Does a "banal Python questions
list" or a "Python beginners list" exist?

2. There is somewhere a very patient fellow willing to
be my free "python tutor" by personal e-mailing
outside the mail list? . The ideal candidate would be
someone, sharing with me some other fields of interest
(I'm a middle-aged Italian pathologist, with some
dBase III and dBase IV past programming experience,
and I like nature and mainly horses). 

Thanks

Alessandro Brollo







___ 
Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
http://mail.yahoo.it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter grid layout

2005-07-07 Thread Eric Brunel
On Wed, 06 Jul 2005 16:32:42 GMT, William Gill <[EMAIL PROTECTED]> wrote:

> Excuse me for intruding, but I followed examples and ended up with a
> similar architecture:
>
>  from Tkinter import *
>  class MyMain(Frame):
>  def __init__(self, master):
>  self.root = master
>  self.master=master
>  root = Tk()
>  app = MyMain(root)
>  app.master.title("Object Editor")
>  root.mainloop()
>
> Erick, are you saying it should be modified to something like :
>
>  from Tkinter import *
>  class MyMain(Tk):
>  ...
>  ...
>  app = MyMain()
>  app.title("My App")
>  app.mainloop()

Well, basically, that's what I'm saying; but your example is a bit better than 
the OP's.

Basically, the problem is that an instance of MyMain will just be some kind of 
graphical component that can be inserted into basically anything. So nothing 
prevents me to do for example:

root = Tk()
Label(root, text='This is my application').pack(side=TOP)
frm = Frame(root)
frm.pack(side=TOP)
app = MyMain(frm)
# You don't show where you pack or grid your MayMain instance in its
# parent, so I'm doing it explicitely here...
app.pack()
root.mainloop()

So the container for MyMain is a Tk instance in your example, and a Frame 
instance in mine. And it works, because it's basically the use case for Frame 
sub-classes: they can be pack'ed or grid'ed or place'd into anything.

So MyMain cannot make any assumption on its container (self.master in your 
first example), since it can be any valid container. So there are many things 
that you just can't do in MyMain, because you don't have a window. For example, 
you can't set the window title, or define a menu bar, since all these are 
defined via methods only available on windows, i.e. Tk or Toplevel instances.

Basically, you did this right, since you call app.master.title(...) in the main 
script, where you know that app.master is a Tk instance. But what can be the 
reason to do it *outside* MyMain? Isn't it the window itself that knows what 
title it should have?

So in your second version, you can do:

 from Tkinter import *
class MyMain(Tk):
   Tk.__init__(self)
   self.title("My App")
   ...
...
app = MyMain()
app.mainloop()

And this always works: since an instance of MyMain is an instance of Tk, you do 
have a window on which to call title. Note that this cannot be safely done in 
your first version, since self.master may not have a title method (see my 
example above).

So you should really stick to the following rules:
- If you write a class defining the main window for your application, make it 
inherit from Tkinter.Tk
- If you write a class defining a "secondary" window for your application, make 
it inherit from Tkinter.Toplevel
- If you write a class defining a graphical component that can be placed 
anywhere in a GUI, make it inherit from Tkinter.Frame
This is basically just a matter of good OO programming: you should choose the 
most accurate super-classes for the classes you define, or someday, you'll run 
into problems...

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Do a "Python beginners e-mail list" exist?

2005-07-07 Thread Gerald Klix
Perhaps irc://irc.freenode.net##python
Note the double #

This channel is less crowed as the #python channels are.

Alessandro Brollo schrieb:
> Far from a professional programmer, I'm simply a
> newbie Python user. Two basic questions:
> 
> 1. I don't want to post banal questions about Python
> to main Python list. Does a "banal Python questions
> list" or a "Python beginners list" exist?
> 
> 2. There is somewhere a very patient fellow willing to
> be my free "python tutor" by personal e-mailing
> outside the mail list? . The ideal candidate would be
> someone, sharing with me some other fields of interest
> (I'm a middle-aged Italian pathologist, with some
> dBase III and dBase IV past programming experience,
> and I like nature and mainly horses). 
> 
> Thanks
> 
> Alessandro Brollo
> 
> 
> 
>   
> 
>   
>   
> ___ 
> Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB 
> http://mail.yahoo.it

-- 
GPG-Key: http://keyserver.veridis.com:11371/search?q=0xA140D634

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


Re: Do a "Python beginners e-mail list" exist?

2005-07-07 Thread John Machin
Alessandro Brollo wrote:
> Far from a professional programmer, I'm simply a
> newbie Python user. Two basic questions:
> 
> 1. I don't want to post banal questions about Python
> to main Python list. Does a "banal Python questions
> list" or a "Python beginners list" exist?

http://mail.python.org/mailman/listinfo/tutor

> 
> 2. There is somewhere a very patient fellow willing to
> be my free "python tutor" by personal e-mailing
> outside the mail list?

See above, where the possibility of one-on-one tutorials is canvassed.

> The ideal candidate would be
> someone, sharing with me some other fields of interest
> (I'm a middle-aged Italian pathologist, with some
> dBase III and dBase IV past programming experience,
> and I like nature and mainly horses). 

There are other newsgroups that cater for your interests e.g. 
rec.equestrian -- check out Google groups.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you program in Python?

2005-07-07 Thread Jorgen Grahn
On Wed, 6 Jul 2005 14:56:09 +0200, Sybren Stuvel <[EMAIL PROTECTED]> wrote:
...
> I'm usually annoyed by IDEs because, for instance, they don't use VIM
> as an editor. Since I'm hooked to that, all IDEs I've used so far have
> failed to impress me.

Same here (s/VIM/Emacs/, or course).

I try not to make myself too dependent on some specialized software, because
(a) I tend to work on different Linux or Unix machines, or even on Windows
and (b) my development cycle is almost the same whether I'm programming in
Python, Perl, C++ or C (or writing in HTML, troff or LaTeX, for that
matter).

Emacs and vim are almost always installed, or trivially installable. All I
need to remember is to bring my emacs config file.

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Do a "Python beginners e-mail list" exist?

2005-07-07 Thread Tony Meyer
> 1. I don't want to post banal questions about Python
> to main Python list. Does a "banal Python questions
> list" or a "Python beginners list" exist?

Yes:



There are plenty of people there that will be glad to help!

=Tony.Meyer

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


Re: Conditionally implementing __iter__ in new style classes

2005-07-07 Thread Thomas Heller
[EMAIL PROTECTED] (Bengt Richter) writes:

> On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller <[EMAIL PROTECTED]> wrote:
>
>>I'm trying to implement __iter__ on an abstract base class while I don't
>>know whether subclasses support that or not.

> Will a property or custom descriptor do what you want? E.g.
>
>  >>> class Base(object):
>  ... def __getIter(self):
>  ... if hasattr(self, "Iterator"):
>  ... return self.Iterator
>  ... raise AttributeError, name
>  ... __iter__ = property(__getIter)
>  ...
>  >>> class Concrete(Base):
>  ... def Iterator(self):
>  ... yield 1
>  ... yield 2
>  ... yield 3
>  ...
>  >>> iter(Base())
>  Traceback (most recent call last):
>File "", line 1, in ?
>  TypeError: iteration over non-sequence
>  >>> iter(Concrete())
>  
>  >>> list(iter(Concrete()))
>  [1, 2, 3]

Yep, that's exactly what I need - thanks.

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


Re: Do a "Python beginners e-mail list" exist?

2005-07-07 Thread Brian van den Broek
Alessandro Brollo said unto the world upon 07/07/2005 03:24:
> Far from a professional programmer, I'm simply a
> newbie Python user. Two basic questions:
> 
> 1. I don't want to post banal questions about Python
> to main Python list. Does a "banal Python questions
> list" or a "Python beginners list" exist?



Check out the Tutor list 

Best,

Brian vdB

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


Re: Lisp development with macros faster than Python development?..

2005-07-07 Thread Antoon Pardon
Op 2005-07-07, Philippe C. Martin schreef <[EMAIL PROTECTED]>:
> 
>
> Almost sounds like a racist comment - sorry if I misunderstood

I'll clarify. A lot of the time I hear arguments against 
features that boils down to.

1) I don't need it.

2) Having the feature will make my job more difficult.

3) I don't understand the merrits of the feature or I
   have difficulty understanding what it does when I
   encounter it.

IMO these are arguments if followed sufficiently will lead to
a language that is only usefull for mediocre programmers.

> Antoon Pardon wrote:
>
>> Op 2005-07-06, Michele Simionato schreef <[EMAIL PROTECTED]>:
>>> Fuzzyman:
 So Lisp is for really good programmers, and Python is for
 mediocre programmers ?
>>>
>>>
>>> Python is *also* for mediocre programmers. I see this as a
>>> strength, not as a weakness.
>> 
>> But sometimes I get the impression people want it to evolve
>> so it is only for mediocre programmers.
>> 
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Steven D'Aprano
Steven Bethard wrote:

> If you're really afraid of two lines, write it as:
> 
> def r(): randint(1, 100)
> 
> This is definitely a bad case for an anonymous function because it's not 
> anonymous!  You give it a name, r.

This is something I've never understood. Why is it bad 
form to assign an "anonymous function" (an object) to a 
name?

It isn't just that lambda _can_ create functions that 
aren't bound to any name. That I get. But why is it 
suppose to be wrong to bind such a function to a name?

Sure, if the lambda is so complicated that it becomes 
unreadable, the usage case is wrong and a def should be 
used instead. But I see nothing wrong with doing this:

func = lambda x: x**3 - 3*x**2

Why is it considered abuse of lambda to assign the 
functions to a name? Is it an abuse of lambda to do this?

D = {"one": lambda noun: noun,
 "two": lambda noun: noun + 's',
 "many": lambda noun: 'lots of ' + noun + 's' }

assert D["two"]("python") == "pythons"


-- 
Steven.

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


Re: Use cases for del

2005-07-07 Thread Steven D'Aprano
Ron Adam wrote:

> Why would you want to use None as an integer value?
> 
> If a value isn't established yet, then do you need the name defined? 
> Wouldn't it be better to wait until you need the name then give it a value?

Er, maybe I'm misunderstanding something here, but 
surely the most obvious case is for default and special 
function arguments:

def count_records(record_obj, start=0, end=None):
 if end == None:
 end = len(record_obj)
 if start == None:  # this is not the default!
 # start at the current position
 start = record_obj.current
 n = 0
 for rec in record_obj.data[start:end]:
 if not rec.isblank():
 n += 1
 return n

which you call with:

# current position to end
count_records(myRecords, None)
# start to end
count_records(myRecords)
# start to current position
count_records(myRecords, end=myRecords.current)

-- 
Steven.

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


Re: How do you program in Python?

2005-07-07 Thread Gregory Bond
Jorgen Grahn wrote:

> Emacs and vim are almost always installed, or trivially installable. All I
> need to remember is to bring my emacs config file.

And, fortunately, USB pen drives are now big enough to hold it!
-- 
http://mail.python.org/mailman/listinfo/python-list


HELP!

2005-07-07 Thread Ert Ert
Please help me i down loaded python nd itplays on MS-DOS mode and not on normal 
please help




 [EMAIL PROTECTED]


-- 
___
Sign-up for Ads Free at Mail.com
http://promo.mail.com/adsfreejump.htm

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


Re: Create datetime instance using a tuple.

2005-07-07 Thread Negroup
> 
> Use:
> dt =3D datetime(*t)
> 

Thanks for the quick reply. 
I can't find any doc about '*' used in this context. Have you some url
or suggestion for which terms search in Google?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: latex/bibtex python paper?

2005-07-07 Thread Jorgen Grahn
On 6 Jul 2005 08:28:45 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> Does anyone have a good template that I might use for writing a python
> paper in latex/bibtex?  I've got the paper mostly done, but am having
> issues with the references.  I am definitely not an expert at
> latex/bibtex.  Right now, I have references defined like this:
...
>
> When I cite these, I get something like this (Foundation[2005]).  Is
> anyone willing to offer up a tarball of a complete paper with sty and
> bst that would make for a nice python paper?

You really, really should Google around for BibTeX information, or ask in a
TeX newsgroup. (Unless I misunderstood you, and Python is somehow involved
as something more than the subject of your paper?)

I have used BibTeX in the past, but forgotten the details. Getting the exact
citation style you want is tricky (and you didn't even say what you wanted
the citations to look like).  There seem to be many newer, contributed
styles which aren't trivial to find without help.

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HELP!

2005-07-07 Thread Robert Kern
Ert Ert wrote:
> Please help me i down loaded python nd itplays on MS-DOS mode and not on 
> normal please help

So what's your problem? Please read

   http://www.catb.org/~esr/faqs/smart-questions.html

Then reformulate your question so that we can answer it.

-- 
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: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Duncan Booth
Steven D'Aprano wrote:
> This is something I've never understood. Why is it bad 
> form to assign an "anonymous function" (an object) to a 
> name?

Because it obfuscates your code for no benefit. You should avoid making it 
hard for others to read your code (and 'others' includes yourself in the 
future).

Also, it obfuscates tracebacks: all lambda expressions will identify in 
tracebacks as , but if you define a function you can give it a 
meaningful name.

> 
> Why is it considered abuse of lambda to assign the 
> functions to a name? Is it an abuse of lambda to do this?
> 
> D = {"one": lambda noun: noun,
>  "two": lambda noun: noun + 's',
>  "many": lambda noun: 'lots of ' + noun + 's' }
> 
> assert D["two"]("python") == "pythons"
> 
> 
No, that is approaching a reasonable use of lambda, however I would still 
be inclined to write it with functions. e.g.

   def one(noun):
   return noun

   def two(noun):
   return noun+'s'

   def many(noun):
   return 'lots of %ss' % (noun,)

   D = dict(one=one, two=two, many=many)

although in this particular case I would probably just put format strings 
in the dictionary:

  def D(style, noun):
 formats = dict(one="%s", two="%ss", many="lots of %ss")
 return formats.get(style, "an indeterminate number of %ss") % (noun,)

  assert D("two","python") == "pythons"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Do a "Python beginners e-mail list" exist?

2005-07-07 Thread Giovanni Dall'Olio
Hi, have you seen the python ML at www.python.it? It's in Italian. You
can find even other tutorial for beginners here.
See also www.zonapython.it

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


Re: Create datetime instance using a tuple.

2005-07-07 Thread John Machin
Negroup wrote:
>>Use:
>>dt =3D datetime(*t)
>>
> 
> 
> Thanks for the quick reply. 
> I can't find any doc about '*' used in this context. Have you some url
> or suggestion for which terms search in Google?

http://www.python.org/doc/2.4.1/tut/tut.html

Then read this section

4.7.4 Unpacking Argument Lists

Then read all the other sections :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: python-constraint 1.0

2005-07-07 Thread gabriele renzi
Gustavo Niemeyer ha scritto:
> 
> Overview
> 
> 
> **python-constraint** [1]_ is a Python module offering solvers for
> Constraint Solving Problems (CSPs) over finite domains in simple
> and pure Python. CSP is class of problems which may be represented
> in terms of variables (`a`, `b`, ...), domains (`a in [1, 2, 3]`, ...),
> and constraints (`a < b`, ...).

This sound cool, but have you noticed logilab.constraint? Care to contrast?
-- 
http://mail.python.org/mailman/listinfo/python-list


How to use Adobe Illustrator Export function within a Python script

2005-07-07 Thread adder
I would like to create a script that can export ai-files to jpg-files
using the export function available in Adobe Illustrator. Can someone
tell me how to dispatch the illustrator com-object to make this
possible and possibly provide me with some tips on how to accomplish
this?!
Thanks in advance
All

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


Re: HELP!

2005-07-07 Thread Giovanni Dall'Olio

Ahah, I've to save this page.


p.s. @ Ert Ert: download this:
http://starship.python.net/crew/mhammond/win32/ and use 'Pythonwin'
(or, use Unix!)

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


Re: map/filter/reduce/lambda opinions and background unscientificmini-survey

2005-07-07 Thread Chris Rebert (cybercobra)
Agreed, I dislike map and its ilk as well.
However, they are handy in some cases. I particularly like the way Ruby
deals with this problem. Instead of all these functions, internal
iterators and true anonymous blocks are used.
Case in point:

def gt_than_5(obj):
return obj > 5
results = filter(gt_than_5, seq)

becomes

results = seq.find_all do |item|
  item > 5
end

This has the advantage of writing less code for the common cases by
having them builtin to the class. Instead of everyone needlessly
recoding these over and over again, they're implemented in one place.
This could be done by defining an abstract class that enumerable
objects inherit from. It's not practical, but I can dream, can't I? ;-)
Also, you don't have to define a separate testing function. Granted, in
this case, the test func is trivial, but when it's non-trivial, you
really notice the advantages.

Ivan Van Laningham wrote:
> Hi All--
>
> Tom Anderson wrote:
> >
> > Comrades,
> >
> > "I expect tons of disagreement in the feedback, all from ex-Lisp-or-Scheme
> > folks. :-)"
> >
> > I disagree strongly with Guido's proposals, and i am not an ex-Lisp,
> > -Scheme or -any-other-functional-language programmer; my only other real
> > language is Java. I wonder if i'm an outlier.
> >
> > So, if you're a pythonista who loves map and lambda, and disagrees with
> > Guido, what's your background? Functional or not?
> >
>
> I'm a pythonista who doesn't love them.  In fact, even though I've done
> more than my fair share of lambda Tkinter programming using lambdas,
> I've never been happy with lambda.  And I've spent months inside of
> Lisp/Emacs Lisp/Scheme, too (I have the world's second largest .emacs
> file [my friend Andy Glew has the largest], even though I can't use it
> on Windows;-).  I find list comprehensions easier to understand than
> map, and small named functions or, better yet, class methods, *tons*
> easier to read/understand than lambda--there are too many restrictions
> you have to remember.
>
> Personally, I find that Lisp & its derivatives put your head in a very
> weird place.  Even weirder than PostScript/Forth/RPN, when you come
> right down to it.
>
> I won't miss them, but since I don't use them now, that doesn't mean a
> whole lot.
>
> Metta,
> Ivan
> --
> Ivan Van Laningham
> God N Locomotive Works
> http://www.andi-holmes.com/
> http://www.foretec.com/python/workshops/1998-11/proceedings.html
> Army Signal Corps:  Cu Chi, Class of '70
> Author:  Teach Yourself Python in 24 Hours

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


Re: f*cking re module

2005-07-07 Thread Chris Smith
> "Michael" == Michael Hoffman <[EMAIL PROTECTED]> writes:

Michael> Greg Lindstrom wrote:
>> I hear that Perl 6 is going to have a rewrite of regular
>> expressions; it will be interesting to see what their hard work
>> produces.

Michael>  From what I saw a while ago, it didn't look like it
Michael> would be any simpler or more elegant. But that was a
Michael> while ago.  -- Michael Hoffman

Oh, come on:  what's a Perliodic Table of Operators, between friends?
http://www.ozonehouse.com/mark/blog/code/PeriodicTable.html
R,
C
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python exception hook simple example needed

2005-07-07 Thread Fuzzyman
Do you have an exception handling dialog ?

Can you use the UI layer without being tied to the rest of the
framework ? They seemed pretty integrated to me.
 
Best Regards,
 
Fuzzy
http://www.voidspace.org.uk/pythonhave an

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


VC++ linking problem

2005-07-07 Thread J
Hi everyone,

I started embedding python into a 3D graphics App and I came
across this linking problem.


SO.lib(ScnGlobal.obj) : error LNK2001: unresolved external symbol
__imp__Py_InitModule4TraceRefs
SO.lib(ScnNode.obj) : error LNK2001: unresolved external symbol
__imp___Py_RefTotal
SO.lib(ScnLight.obj) : error LNK2001: unresolved external symbol
__imp___Py_RefTotal

I am linking against python24.lib using VC++ 6.0. Before I got to this
point it couldn't find python24_d.lib. After searching around
for a while I came across a solution that included changing
python24_d.lib to python24.lib in one of the header files. I hope that
didn't have a negative effect. I would really appreciate
some help


Thanks
Jochen

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


Re: VC++ linking problem

2005-07-07 Thread Gerhard Haering
On Thu, Jul 07, 2005 at 04:52:11AM -0700, J wrote:
> Hi everyone,
> 
> I started embedding python into a 3D graphics App and I came
> across this linking problem.
> 
> 
> SO.lib(ScnGlobal.obj) : error LNK2001: unresolved external symbol
> __imp__Py_InitModule4TraceRefs
> SO.lib(ScnNode.obj) : error LNK2001: unresolved external symbol
> __imp___Py_RefTotal
> SO.lib(ScnLight.obj) : error LNK2001: unresolved external symbol
> __imp___Py_RefTotal
> 
> I am linking against python24.lib using VC++ 6.0. Before I got to this
> point it couldn't find python24_d.lib. After searching around
> for a while I came across a solution that included changing
> python24_d.lib to python24.lib in one of the header files. I hope that
> didn't have a negative effect. I would really appreciate
> some help

It *does* have a negative effect. Python debug and non-debug libraries
are not binary compatible, even when otherwise compiled with the same
settings. I think that's the reason for the _d suffixes for Python debug
binaries on Windows.

The solution for you is to compile yourself a debug version of Python
for testing your whole app in debug mode.

AFAIR in python-dev Python 2.4 can still be compiled with MSVC6, even
though the official binaries are built with MSVC 7.1.

-- Gerhard
-- 
Gerhard Häring - [EMAIL PROTECTED] - Python, web & database development


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: VC++ linking problem

2005-07-07 Thread Miki Tebeka
Hello Jochen,

> I started embedding python into a 3D graphics App and I came
> across this linking problem.
> 
> 
> SO.lib(ScnGlobal.obj) : error LNK2001: unresolved external symbol
> __imp__Py_InitModule4TraceRefs
> SO.lib(ScnNode.obj) : error LNK2001: unresolved external symbol
> __imp___Py_RefTotal
> SO.lib(ScnLight.obj) : error LNK2001: unresolved external symbol
> __imp___Py_RefTotal
> 
> I am linking against python24.lib using VC++ 6.0. Before I got to this
> point it couldn't find python24_d.lib. After searching around
> for a while I came across a solution that included changing
> python24_d.lib to python24.lib in one of the header files. I hope that
> didn't have a negative effect. I would really appreciate
> some help
This is since Python header file is in debug mode and you link with the
regular library.

Just do:
#undef _DEBUG /* Link with python24.lib and not python24_d.lib */
#include 

and you'll be fine.

IMO python should try and link with python24.lib when compiling in debug
mode since we want to debug our program and not Python.

Bye.
--

Miki Tebeka <[EMAIL PROTECTED]>
http://tebeka.bizhat.com
The only difference between children and adults is the price of the toys


pgps6D8NhH5ez.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

how to change a script while it is running

2005-07-07 Thread faxme
Hi, I would like to know if it is possible to change code on the fly on a 
python interpreter. I want to have a python script running a multithread 
server and be able to connect to this python script and change the 
interpreter environment. Is this possible?
Ideally i would like to call python, load the script inside the python 
command line and while the script works still be able to type other python 
commands(that might change the running script).

Thanks 


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


Re: Favorite non-python language trick?

2005-07-07 Thread Edvard Majakari
Simon Brunning <[EMAIL PROTECTED]> writes:

> http://wiki.python.org/moin/PythonDecoratorLibrary?#head-de01988728ccdec415708f10928cc6feb022e7bb

Neat.

I guess about 75% about programming-related things classified as neat-o or
"convenient!" are already implemented by some Pythonista(s). Spoils all the
fun for reinventing the wheel, doesn't it. :)

-- 
# Edvard Majakari   Software Engineer
# PGP PUBLIC KEY available  Soli Deo Gloria!

$_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print
join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n";
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Favorite non-python language trick?

2005-07-07 Thread Shai
Mike Meyer wrote:
> "Shai" <[EMAIL PROTECTED]> writes:
>
> > They're called "Special vars", and you need to define them (unlike
> > local LISP variables, which behave essentially like Python vars), but
> > then you use them just like other vars (that is, you usually bind them
> > with LET). This is the first I hear about them being ill-considered in
> > LISP; http://www.gigamonkeys.com/book/ is a recently published LISP
> > book which recommends them. I don't know about Scheme, but I think it
> > does have them.
>
> I'm pretty sure scheme doesn't have dynamically bound variables. I
> just went through r5rs to check, and couldn't find them.
>

Yes, you're right. One learns.

> > dynamic x=10
> > def bar():
> >   print x
> >
>
> This looks different from what I understood before. You're now
> declaring the variable dynamic in the global scope, rather than in the
> function that makes it dynamic. This is a *much* more palatable
> situation.
>

This is indeed different from what I said first. It copies the Common
LISP construct without regard to consistency with the Python global
construct.

> Globals are lexically scoped. As such, you can find the defintion of
> the variable by examining the module that includes the function. Yes,
> other modules can reach into your module and change them - but you can
> find those, because they reference your module by name.
>
> A dynamic variable declared so in a function has no such clue
> associated with it. If the variable is declared dynamic in the module
> of the enclosed function, that provides a contextual clue.

In my original proposal, dynamic variables are seen as globals from the
function in their module which reads them; no more, no less. The
important point I want from dynamic scope is the time-locality of
asignments, that
is, the fact that they are undone when the (lexical) scope of the new
binding ends. This allows the use of globals, with a lot less fear of
unintended interactions between users of the module (well, this is only
accurate until multithreading enters the picture, but that can be
handled
too).

[rest snipped]

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


Re: VC++ linking problem

2005-07-07 Thread Wolfgang Langner
Hello Jochen,

> I started embedding python into a 3D graphics App and I came
> across this linking problem.
> 
> 
> SO.lib(ScnGlobal.obj) : error LNK2001: unresolved external symbol
> __imp__Py_InitModule4TraceRefs
> SO.lib(ScnNode.obj) : error LNK2001: unresolved external symbol
> __imp___Py_RefTotal
> SO.lib(ScnLight.obj) : error LNK2001: unresolved external symbol
> __imp___Py_RefTotal
> 
> I am linking against python24.lib using VC++ 6.0. Before I got to this
> point it couldn't find python24_d.lib. After searching around
> for a while I came across a solution that included changing
> python24_d.lib to python24.lib in one of the header files. I hope that
> didn't have a negative effect. I would really appreciate
> some help

Be careful, python 2.4 is build with VC++ 7.1.
Mixing this in your application which is build with
VC++ 6.0 can lead to trouble.

python24_d.lib is the debug version of the python library.
It's possible to build your application in debug against a
release Python Version. But I don't know what switches are needed.

This unresolved external symbols are a result of your linkage.
This symbols are only present in the debug version of the library.
If you start python_d.exe (debug executable of python) you get
the total ref count after every statement.

To fix this, build debug version of your App against debug version
of python or set all switches to build a debug version against release
python.
The boost python library does this, see:
http://www.boost.org/libs/python/doc/index.html


bye by Wolfgang
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Modules for inclusion in standard library?

2005-07-07 Thread awbarker
1. LDAP module should be included in the base distro.
2. DNS library really should be included in the base library, I emailed
Anthony Baxter and he replied, saying it was almost done.
3. Ipython would be nice

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


Re: VC++ linking problem

2005-07-07 Thread J
Thank you very much Miki!

That was an easy solution. It links... I will put a hold on compiling
the latest version until I really have to. I will probably switch to VC
7 before that.

Cheers
Jochen


Miki Tebeka wrote:
> Hello Jochen,
>
> > I started embedding python into a 3D graphics App and I came
> > across this linking problem.
> >
> >
> > SO.lib(ScnGlobal.obj) : error LNK2001: unresolved external symbol
> > __imp__Py_InitModule4TraceRefs
> > SO.lib(ScnNode.obj) : error LNK2001: unresolved external symbol
> > __imp___Py_RefTotal
> > SO.lib(ScnLight.obj) : error LNK2001: unresolved external symbol
> > __imp___Py_RefTotal
> >
> > I am linking against python24.lib using VC++ 6.0. Before I got to this
> > point it couldn't find python24_d.lib. After searching around
> > for a while I came across a solution that included changing
> > python24_d.lib to python24.lib in one of the header files. I hope that
> > didn't have a negative effect. I would really appreciate
> > some help
> This is since Python header file is in debug mode and you link with the
> regular library.
>
> Just do:
> #undef _DEBUG /* Link with python24.lib and not python24_d.lib */
> #include 
>
> and you'll be fine.
>
> IMO python should try and link with python24.lib when compiling in debug
> mode since we want to debug our program and not Python.
>
> Bye.
> --
> 
> Miki Tebeka <[EMAIL PROTECTED]>
> http://tebeka.bizhat.com
> The only difference between children and adults is the price of the toys

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


Windows Cmd.exe Window

2005-07-07 Thread Giles Brown
For my sins I'm a MS Windows user at work and apart from that I have a
small problem ...

I like to write python scripts to do small tasks and then double click
on them from the file explorer to run them.

Unfortunately I'm not perfect and sometimes I make mistakes and have
unhandled exceptions or syntax errors when running the scripts.  The
default behaviour is to shut down the command window which leaves you
no chance of reading the exception.

In the past I have created .bat wrapper files that just call the python
interpreter, but it is a bit tedious to have to create a matching .bat
file for every script.  So I came up with the following approach...

1. Copy python.exe to pythoncmd.exe
2. Add a bit of stuff to sitecustomize.py
3. Add a special first line to every python script and give it a .cmd
extension.

The stuff added to sitecustomize.py (actually I created a
sitecustomize.py for this) is:
"""
import sys
import os

if os.path.basename(sys.executable) == 'pythoncmd.exe':

def cmdexcepthook(*args):
sys.__excepthook__(*args)
# Let use confirm/inspect error
os.system('pause')

sys.excepthook = cmdexcepthook
"""

The special first line is:

@pythoncmd -x "%~f0" %* & exit /b

(In the python.org FAQ for windows it says
@setlocal enableextensions & python -x %~f0 %* & goto :EOF
but since I have no idea which is "right" I chose the simpler looking
one)

This approach does require pythoncmd.exe to by in your %PATH% but I
think that is reasonable ;)

I am a bit disappointed I couldn't think of a way of deciding if I was
running a ".cmd" file in sitecustomize.py so that I could just use the
normal python.exe.  Using a renamed interpreter .exe is just a trick
for detecting when I am running .cmd files, but it means that the
script won't run on another machine that hasn't had the python.exe
copied to pythoncmd.exe on it.  Which is a shame.

So my question.  Is there a better way?  I'm not really happy with this
approach.  Should I stop worrying and go and play my new ukulele?
Answers please.

Giles

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


Re: Windows Cmd.exe Window

2005-07-07 Thread Thorsten Kampe
* Giles Brown (2005-07-07 13:56 +0100)
> For my sins I'm a MS Windows user at work and apart from that I have a
> small problem ...
> 
> I like to write python scripts to do small tasks and then double click
> on them from the file explorer to run them.
> 
> Unfortunately I'm not perfect and sometimes I make mistakes and have
> unhandled exceptions or syntax errors when running the scripts.  The
> default behaviour is to shut down the command window which leaves you
> no chance of reading the exception.
> 
> In the past I have created .bat wrapper files that just call the python
> interpreter, but it is a bit tedious to have to create a matching .bat
> file for every script.  So I came up with the following approach...
> 
> 1. Copy python.exe to pythoncmd.exe
> 2. Add a bit of stuff to sitecustomize.py
> 3. Add a special first line to every python script and give it a .cmd
> extension.
> 
> The stuff added to sitecustomize.py (actually I created a
> sitecustomize.py for this) is:
> """
> import sys
> import os
> 
> if os.path.basename(sys.executable) == 'pythoncmd.exe':
> 
> def cmdexcepthook(*args):
> sys.__excepthook__(*args)
> # Let use confirm/inspect error
> os.system('pause')
> 
> sys.excepthook = cmdexcepthook
> """
> 
> The special first line is:
> 
> @pythoncmd -x "%~f0" %* & exit /b
> 
> (In the python.org FAQ for windows it says
> @setlocal enableextensions & python -x %~f0 %* & goto :EOF
> but since I have no idea which is "right" I chose the simpler looking
> one)
> 
> This approach does require pythoncmd.exe to by in your %PATH% but I
> think that is reasonable ;)
> 
> I am a bit disappointed I couldn't think of a way of deciding if I was
> running a ".cmd" file in sitecustomize.py so that I could just use the
> normal python.exe.  Using a renamed interpreter .exe is just a trick
> for detecting when I am running .cmd files, but it means that the
> script won't run on another machine that hasn't had the python.exe
> copied to pythoncmd.exe on it.  Which is a shame.
> 
> So my question.  Is there a better way?  I'm not really happy with this
> approach.  Should I stop worrying and go and play my new ukulele?
> Answers please.

I think it's a FAQ to: use raw_input at the end to prevent closing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: calling python procedures from tcl using tclpython

2005-07-07 Thread Michael Schlenker
chand wrote:
> Hi..
> 
> I am writing a Gui in TCL and my backend code is python. I want to call
> python procedure in tcl using tclpyhton. I want to know clearly how
> this should be implemented.
> 
> let's say I have procedure test_function(arg1,arg2 ...) defined in
> test.py.
> I want to call this procedure in tcl. Let me know how this should be
> achieved.
> The doubt basically have is how the tcl code knows in which .py file
> this procedure is defined.
> 
> currently I have wriiten this tcl code which is not working
> 
> package require tclpython
> set interpreter [python::interp new]
> $interpreter eval {def test_function(): arg1,arg2} ;
> python::interp delete $interpreter
> 
What does not work? You never load your file test.py anywhere inside,
you just evaluate 'def test_function(): arg1,arg2' so what are you
expecting to happen?

Your call to '$interpreter eval' lets you call arbitrary python code,
but you have to provide the python code that loads your function
definitions etc. I don't know python, but it should be a trivial code.

Michael


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


Re: Windows Cmd.exe Window

2005-07-07 Thread Giles Brown
Nah.  You're missing my point.  I only want the command window not to
be closed if there is an *exception*.  Picky I know, but there you go.

Giles

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


Re: Strange os.path.exists() behaviour

2005-07-07 Thread Sion Arrowsmith
Jeff Epler  <[EMAIL PROTECTED]> wrote:
>Pierre wrote:
>> Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on wi=
>n32
>   =
>^^^
>Here's the bug.  You're using Windows.  It's a filesystem, but not as we kn=
>ow it...
> [ ... ]
>As you can see, not only does Windows think that "exist" exists, but it=
> can
>successfully "type" its contents too!

The "reason" for this behaviour is that the concept of a file
extension is firmly embedded in the operating system. exists is a
file with no extension, as is exists. (no, it doesn't make a
distinction between "no extension" and "an empty extension").
>From there it's not too great a leap of induction to suppose that
exists is the same file called exists with no extension. It's
not unlike being able to stick an arbitrary number of /s onto the
end of a directory name on a sane OS/filesystem.

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Windows Cmd.exe Window

2005-07-07 Thread harold fellermann

On 07.07.2005, at 15:25, Giles Brown wrote:

> Nah.  You're missing my point.  I only want the command window not to
> be closed if there is an *exception*.  Picky I know, but there you go.

well, then register raw_input as exit function:

 >>> import atexit
 >>> atexit.register(raw_input)

works fine in my terminal. should do in your framework also.

cheers,

- harold -

--
What is mind? -- Doesn't matter.
What is matter? -- Never mind!
--

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


Re: calling python procedures from tcl using tclpython

2005-07-07 Thread chand
That is exactly i want to know. i.e...,how to provide the python code
path in tcl script file, that loads required function.

--BestRegards.,
--chandra

> definitions etc.

Michael Schlenker wrote:
> chand wrote:
> > Hi..
> >
> > I am writing a Gui in TCL and my backend code is python. I want to call
> > python procedure in tcl using tclpyhton. I want to know clearly how
> > this should be implemented.
> >
> > let's say I have procedure test_function(arg1,arg2 ...) defined in
> > test.py.
> > I want to call this procedure in tcl. Let me know how this should be
> > achieved.
> > The doubt basically have is how the tcl code knows in which .py file
> > this procedure is defined.
> >
> > currently I have wriiten this tcl code which is not working
> >
> > package require tclpython
> > set interpreter [python::interp new]
> > $interpreter eval {def test_function(): arg1,arg2} ;
> > python::interp delete $interpreter
> >
> What does not work? You never load your file test.py anywhere inside,
> you just evaluate 'def test_function(): arg1,arg2' so what are you
> expecting to happen?
>
> Your call to '$interpreter eval' lets you call arbitrary python code,
> but you have to provide the python code that loads your function
> definitions etc. I don't know python, but it should be a trivial code.
> 
> Michael

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


Re: Windows Cmd.exe Window

2005-07-07 Thread harold fellermann

On 07.07.2005, at 15:43, harold fellermann wrote:

> On 07.07.2005, at 15:25, Giles Brown wrote:
>
>> Nah.  You're missing my point.  I only want the command window not to
>> be closed if there is an *exception*.  Picky I know, but there you go.
>
> well, then register raw_input as exit function:
>
 import atexit
 atexit.register(raw_input)
>
> works fine in my terminal. should do in your framework also.

sorry, I did not think. if you want to wait for input _only_ if
an exception occured, your exit function needs to check for the
exception:

 >>> import atexit
 >>>
 >>> def wait_on_exc() :
... import sys
... if sys.exc_type :
... raw_input()
...
 >>> atexit.register(wait_on_exc)

this should do the job, now.

- harold -


--
What if nothing exists and everything is an illusion?
In this case I definitely overpayed my new carpet!
-- Woody Allen

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


Re: Windows Cmd.exe Window

2005-07-07 Thread Larry Bates
Use sys.excepthook to hook a function you define and in that function
print a traceback and pause before exiting. Something like (not tested
but copied from working example):

import sys
def Myexcepthook(type, value, traceback):
print "in Myexcepthook-type=", type," value=",value," traceback=",traceback
import traceback
lines=traceback.format_exception(type, value, traceback)
print "-Traceback lines---"
print "\n".join(lines)
print "---"
t=raw_input("Press return to continue")
sys.exit(2)

#
# set sys.excepthook
#
sys.excepthook=Myexcepthook
#
# create an uncaught divide by zero exception
#
a=1/0


-Larry Bates

Giles Brown wrote:
> For my sins I'm a MS Windows user at work and apart from that I have a
> small problem ...
> 
> I like to write python scripts to do small tasks and then double click
> on them from the file explorer to run them.
> 
> Unfortunately I'm not perfect and sometimes I make mistakes and have
> unhandled exceptions or syntax errors when running the scripts.  The
> default behaviour is to shut down the command window which leaves you
> no chance of reading the exception.
> 
> In the past I have created .bat wrapper files that just call the python
> interpreter, but it is a bit tedious to have to create a matching .bat
> file for every script.  So I came up with the following approach...
> 
> 1. Copy python.exe to pythoncmd.exe
> 2. Add a bit of stuff to sitecustomize.py
> 3. Add a special first line to every python script and give it a .cmd
> extension.
> 
> The stuff added to sitecustomize.py (actually I created a
> sitecustomize.py for this) is:
> """
> import sys
> import os
> 
> if os.path.basename(sys.executable) == 'pythoncmd.exe':
> 
> def cmdexcepthook(*args):
> sys.__excepthook__(*args)
> # Let use confirm/inspect error
> os.system('pause')
> 
> sys.excepthook = cmdexcepthook
> """
> 
> The special first line is:
> 
> @pythoncmd -x "%~f0" %* & exit /b
> 
> (In the python.org FAQ for windows it says
> @setlocal enableextensions & python -x %~f0 %* & goto :EOF
> but since I have no idea which is "right" I chose the simpler looking
> one)
> 
> This approach does require pythoncmd.exe to by in your %PATH% but I
> think that is reasonable ;)
> 
> I am a bit disappointed I couldn't think of a way of deciding if I was
> running a ".cmd" file in sitecustomize.py so that I could just use the
> normal python.exe.  Using a renamed interpreter .exe is just a trick
> for detecting when I am running .cmd files, but it means that the
> script won't run on another machine that hasn't had the python.exe
> copied to pythoncmd.exe on it.  Which is a shame.
> 
> So my question.  Is there a better way?  I'm not really happy with this
> approach.  Should I stop worrying and go and play my new ukulele?
> Answers please.
> 
> Giles
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Determining actual elapsed (wall-clock) time

2005-07-07 Thread zooko
The traditional use of gettimeofday() to (insecurely and unreliably)
approximate elapsed local time is one of my pet peeves.

Fortunately a real monotonic clock has finally been added to the linux
kernel and glibc:

http://www.imperialviolet.org/page24.html#e474

If you have a recent enough kernel and glibc you can use that.  On
Windows you can use system timers and handle wraparound yourself.

And you can write an abstract Pythonic layer over both and give it to
me.  ;-)

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


Re: ANN: python-constraint 1.0

2005-07-07 Thread Benji York
Gustavo Niemeyer wrote:
> **python-constraint** [1]_ is a Python module offering solvers for
> Constraint Solving Problems (CSPs) over finite domains in simple
> and pure Python. 

Very cool!  I can't wait to get some time to play with this.
-- 
Benji York


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


Re: Windows Cmd.exe Window

2005-07-07 Thread Giles Brown
Thanks for your replies.

I think we might have a miscommunication here as (to my understanding)
neither of your replies actually solve my problem.

After all, the function raw_input is just another way of blocking until
user input.  I was already doing that using "os.system('pause')".

To recap, what I'm looking for is a way of setting up specific scripts
(not every script) so that when I double click on it, it runs, but if
there is an exception (even a SyntaxError in the top level script) I
get a traceback in a window that doesn't disappear immediately.

The tricky elements of this are:
1) It can't be done using code in the script itself (such as using an
import statement) because in the presence of a SyntaxError the import
statement is never run.  This is why I was looking at sitecustomize.py
2) I don't want to do unusual exception/atexit hooking for every script
and so need to be able to detect when I am running one of these .cmd
type scripts.

I hope this clarifies things.  I had hoped that my question was worded
sufficiently well to indicate this wasn't a straight-down-the-line
newbie question (I've been programming in Python for seven years now).
Obviously it wasn't.  My apologies.

Giles

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


Re: latex/bibtex python paper?

2005-07-07 Thread Florian Diesch
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Does anyone have a good template that I might use for writing a python
> paper in latex/bibtex?  I've got the paper mostly done, but am having
> issues with the references.  I am definitely not an expert at
> latex/bibtex.  Right now, I have references defined like this:
>
> @article{imp,
>   title = {imp -- Access the import internals},
>   journal = "http://www.python.org/doc/current/lib/module-imp.html";,
>   author = {Python Software Foundation},
>   year = {2005}
> }
>
> When I cite these, I get something like this (Foundation[2005]).  Is
> anyone willing to offer up a tarball of a complete paper with sty and
> bst that would make for a nice python paper?

I would use

@Manual{imp,
  title ={imp -- Access the import internals},
  key =  {imp},
  organization = {Python Software Foundation},
  address =  {\url{http://www.python.org/doc/current/lib/module-imp.html}},
  year = 2005
}

You need hyperref for \url.
With \bibliographystyle{apalike} I get imp (2005), but that depends on what
you want your references look like. I think you better ask in a TeX group 
about that. 



   Florian
-- 
begin  signature_virus
 Hi! I'm a signature virus. Please copy me to your signature to help me spread.
end
-- 
http://mail.python.org/mailman/listinfo/python-list


question about introspection using inspect module

2005-07-07 Thread Benjamin Rutt
I'm trying to learn about introspection in Python.  my ultimate goal
is to be able to build a module "text database" of all modules that
are in the sys.path, by discovering all candidate modules (I've
already done that), importing all of them, and then introspecting on
each module to discover its functions, globals and classes.  But for
now I am having a problem with the latter.

I would like to import a module and figure out the names of its
defined functions, globals, and classes.  Here's my attempt, file
foo.py, which has a single function, class, and global defined:

#!/usr/bin/env python

def somefunction(i):
i = i + 1

class someclass:
def __init__(self):
self.x = 0
self.y = 1

someglobal = 1.2

if __name__ == "__main__": # when run as a script
import foo
import inspect
from inspect import *
isfuncs = filter(lambda x: re.match("^is", x) and x, dir(inspect))
print isfuncs
print filter(lambda x: re.match("some", x[0]) and x[0], getmembers(foo))
for f in isfuncs:
exec('print "trying %20s: ",; print getmembers(foo, %s)' % (f, f))

the output of running it as a script is the following:

['isbuiltin', 'isclass', 'iscode', 'isdatadescriptor', 'isframe', 
'isfunction', 'ismethod', 'ismethoddescriptor', 'ismodule', 'isroutine', 
'istraceback']
[('someclass', ), ('somefunction', 
), ('someglobal', 1.2)]
tryingisbuiltin:  []
trying  isclass:  [('someclass', )]
trying   iscode:  []
trying isdatadescriptor:  []
trying  isframe:  []
trying   isfunction:  [('somefunction', )]
trying ismethod:  []
trying   ismethoddescriptor:  []
trying ismodule:  []
tryingisroutine:  [('somefunction', )]
trying  istraceback:  []

I was trying to use inspect.getmembers(foo, ) with an
appropriate predicate ("is" function).  it looks like I am able to
discover that 'someclass' is a class, and that 'somefunction' is a
function (and also a routine, apparently).  However, I cannot seem to
discover that 'someglobal' is a global.  How to do so?  Thanks,
-- 
Benjamin Rutt
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows Cmd.exe Window

2005-07-07 Thread Thomas Heller
"Giles Brown" <[EMAIL PROTECTED]> writes:

> Nah.  You're missing my point.  I only want the command window not to
> be closed if there is an *exception*.  Picky I know, but there you go.

I find it useful to set an sys.excepthook which calls the debugger
pdb.pm().  This way I not only see the traceback, but I can also poke
around in the environment to find the problem.

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


Re: Windows Cmd.exe Window

2005-07-07 Thread Giles Brown
Hi Larry,
I mentioned how I am already using "sys.excepthook" in my initial
posting.
What I'm looking for is:
1) Is there any better way of solving the problem than setting
sys.excepthook in sitecustomize.py?
2) Or is there a better way of detecting when I am running a .cmd based
script than the method I proposed?
Hope this clears up what I'm asking for.
Thanks,
Giles

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


Re: Windows Cmd.exe Window

2005-07-07 Thread Duncan Booth
harold fellermann wrote:

> sorry, I did not think. if you want to wait for input _only_ if
> an exception occured, your exit function needs to check for the
> exception:
> 
> >>> import atexit
> >>>
> >>> def wait_on_exc() :
> ... import sys
> ... if sys.exc_type :
> ... raw_input()
> ...
> >>> atexit.register(wait_on_exc)
> 
> this should do the job, now.
> 

Did you think to test your code before posting it?

sys.exc_type is deprecated (you should use sys.exc_info() instead), but 
neither will tell you whether the program is exiting as a result of an 
exception when called from an atexit function, by the time the atexit 
function is called the exception is no longer accessible.

As Larry Bates suggested, the OP needs to use a sys.excepthook. 
Unfortunately he doesn't test his code either (the parameter 'traceback' 
conflicts with the module 'traceback'), but at least the principle is 
correct.



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


Re: Windows Cmd.exe Window

2005-07-07 Thread Duncan Booth
Giles Brown wrote:

> The special first line is:
> 
> @pythoncmd -x "%~f0" %* & exit /b
> 
> (In the python.org FAQ for windows it says
> @setlocal enableextensions & python -x %~f0 %* & goto :EOF
> but since I have no idea which is "right" I chose the simpler looking
> one)
> 
> This approach does require pythoncmd.exe to by in your %PATH% but I
> think that is reasonable ;)
> 
> I am a bit disappointed I couldn't think of a way of deciding if I was
> running a ".cmd" file in sitecustomize.py so that I could just use the
> normal python.exe.  Using a renamed interpreter .exe is just a trick
> for detecting when I am running .cmd files, but it means that the
> script won't run on another machine that hasn't had the python.exe
> copied to pythoncmd.exe on it.  Which is a shame.

I'm having problems understanding your problem. If the file is a .cmd
file then surely the second line (i.e. the one immediately following the
python -x command) could simply do "import sethook" where sethook would
be a module that sets your excepthook. 

Alternatively you could check at any point whether sys.argv[0] ends with
'.cmd' or '.bat' (after lowercasing). 

> 
> So my question.  Is there a better way?  I'm not really happy with
> this approach.  Should I stop worrying and go and play my new ukulele?
> Answers please.

Go on, upload some ukulele playing somewhere.

BTW, another solution is to push the pause command out to the shell: 

---
@setlocal enableextensions & (python -x %~f0 %* || pause) & goto :EOF

import sys
if len(sys.argv) > 1:
   sys.exit("this will pause")

---
will pause only if the python program terminates with a non-zero exit code. 
This means messages from sys.exit will cause a pause as well as exceptions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use cases for del

2005-07-07 Thread Grant Edwards
On 2005-07-07, Ron Adam <[EMAIL PROTECTED]> wrote:

>>class demo:
>>   def foo(v=None):
>>   if v is not None:
>>   self.v = v
>>   return self.v   
>
> You are really checking if v exists, so having it undefined in
> namespace as the default is consistent with what you are
> doing.
>
> As I said above...
>
> It would be a way to set an argument as being optional without
> actually assigning a value to it.
>
> So it would still work like you expect even though v is not
> bound to anything.  Like I said the bigger problem is that
> globals will be visible and that would create a conflict.
> Setting a value to None in a function hides globals of the
> same name.  That wouldn't happen if None unbound names as del
> does.

Good point.  I hadn't thought of that.

> So you would need to use something else for that purpose I
> suppose, but that was why None became a literal in the first
> place, so maybe it's taking a step backwards.
>
>
>> 2) So I can use it as sort of a NaN equivalent.
>> 
>>if self.fd is None:
>>   self.fd = os.open('foo.bar','w')
>>
>>if self.fd is not None:
>>   os.close(self.fd)
>>   self.fd = None  
>
> It would still work as you expect.  A while back I suggested an 'also' 
> for if that would do exactly that with only one test.  Nobody liked it.
>
>   if self.fd is None:
>  self.fd = os.open('foo.bar','w')
>  # do something with self.fd
>
>   also:
>  os.close(self.fd)
>  self.fd = None
>
>
>>>If a value isn't established yet, then do you need the name
>>>defined?
>>  
>> I find it more obvious to set the name to None during the
>> periods that it isn't valid than to delete it and check for a
>> NameError when I want to know if the value is usable or not.
>
> You would still be able to do that explicitly and it probably would be a 
> good idea when you aren't sure if a name is left over from something else.
>
> If a name is None, it means it's available and unassigned, so
> you don't have to check for a NameError.

How would you spell "if a name is None"?

Personally, I think the spellings

   del name
   if 'name' in locals()

is much more explicit/obvious than

   name = None
   name is None   

I expect the "=" operator to bind a name to a value.  Having it
do something completely different some of the time seems a bit
unpythonic.
   
-- 
Grant Edwards   grante Yow!  Today, THREE WINOS
  at   from DETROIT sold me a
   visi.comframed photo of TAB HUNTER
   before his MAKEOVER!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Do a "Python beginners e-mail list" exist?

2005-07-07 Thread Grant Edwards
On 2005-07-07, Alessandro Brollo <[EMAIL PROTECTED]> wrote:

> Far from a professional programmer, I'm simply a newbie Python
> user. Two basic questions:
>
> 1. I don't want to post banal questions about Python to main
>Python list.

Go ahead.  We're really quite nice.  Extraordinarily so by
Usenet standards.

> Does a "banal Python questions list" or a "Python
> beginners list" exist?

There's a tutor list:

  http://mail.python.org/mailman/listinfo/tutor

> 2. There is somewhere a very patient fellow willing to be my
>free "python tutor" by personal e-mailing outside the mail
>list? . The ideal candidate would be someone, sharing with
>me some other fields of interest (I'm a middle-aged Italian
>pathologist, with some dBase III and dBase IV past
>programming experience, and I like nature and mainly
>horses). 

I guess I'm out, the only thing I can claim is middle-age. :)

We generally encourange questions to be posted in public forums
such as the tutor list or c.l.p so that others can benefit from
the exchange as well.  No matter what you ask, somebody else
will someday want to know the same thing, and Google will find
them the answer if it's in a public forum.

-- 
Grant Edwards   grante Yow!  He is the
  at   MELBA-BEING... the ANGEL
   visi.comCAKE... XEROX him... XEROX
   him --
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows Cmd.exe Window

2005-07-07 Thread Giles Brown
Hooray! We have a winner!

Thanks Duncan.  Your improved shell line will do the job very nicely.
:)

(btw, the problem with "import sethook" at the top of the script is
that syntax errors in the top-level will prevent the import from being
run meaning we don't get our traceback anymore.)

Giles

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


Re: f*cking re module

2005-07-07 Thread Steven D'Aprano
On Thu, 07 Jul 2005 06:47:54 -0400, Chris Smith wrote:

>> "Michael" == Michael Hoffman <[EMAIL PROTECTED]> writes:
> 
> Michael> Greg Lindstrom wrote:
> >> I hear that Perl 6 is going to have a rewrite of regular
> >> expressions; it will be interesting to see what their hard work
> >> produces.
> 
> Michael>  From what I saw a while ago, it didn't look like it
> Michael> would be any simpler or more elegant. But that was a
> Michael> while ago.  -- Michael Hoffman
> 
> Oh, come on:  what's a Perliodic Table of Operators, between friends?
> http://www.ozonehouse.com/mark/blog/code/PeriodicTable.html


That, and the discussion on operators by Larry Wall, are two of the most
scary things I've ever seen. Is there any possible sequence of bytes that
will not be a valid Perl expression or operator?

I was going to suggest a single null byte, but then I realised that it
is probably be an operator for converting a decimal numeric string to an
associative array mapping integers to German verbs.

All jokes aside, thank goodness Guido isn't Larry. Larry actually gives
the thumbs-up to syntax that will confuse programmers:

[quote]
So Perl could keep track of a unary = operator, even if the human
programmer might be confused. So I'd place a unary = operator in the
category of "OK, but don't use it for anything that will cause widespread
confusion."
[end quote]

There is no unary = operator in Perl, yet, but Larry sees nothing wrong
with the concept of syntax that confuses programmers, or of code which can
be parsed as legal code by Perl even if it can't be displayed on the
developer's computer.



-- 
Steven.

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Paweł Sakowski
Tom Anderson wrote:
> def flatten(ll):
>  return reduce(lambda a, l: a.extend(l), ll, [])
> 
> How would one do that as a list comp, by the way? I'm really not very good
> with them yet.

Not really a list-comprehension based solution, but I think what you want is

>>> ll=[[1,2],[3,4,5],[6]]
>>> sum(ll,[])
[1, 2, 3, 4, 5, 6]

-- 
 Paweł Sakowski <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HELP!

2005-07-07 Thread Rocco Moretti
Ert Ert wrote:
> Please help me i down loaded python nd itplays on MS-DOS mode and not on 
> normal please help

Python itself is a command line program. "MS-DOS mode" *is* it's normal 
mode.

As other's have mentioned, there are graphical front ends to Python 
which you may be more comforatble with. You can either download 
something extra, or on the standard windows installer there is an 
Integrated Development Environment (IDE) called Idle.  If you go: Start 
Menu->(All Programs)->Python2.4 one of the icons should be for "IDLE 2.4 
(Python GUI)"

You may also be interested in the python tutor mailing list. You'll find 
that info, along with a bunch of other great stuff, on the python 
website (www.python.org).

If I've misunderstood you, you'll have to clarify what you want.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Steven D'Aprano
On Thu, 07 Jul 2005 09:36:24 +, Duncan Booth wrote:

> Steven D'Aprano wrote:
>> This is something I've never understood. Why is it bad 
>> form to assign an "anonymous function" (an object) to a 
>> name?
> 
> Because it obfuscates your code for no benefit. You should avoid making it 
> hard for others to read your code (and 'others' includes yourself in the 
> future).

I don't particularly think I'm that much smarter than the average
programmer. In fact I *know* that I'm not that much smarter. So why do I
see nothing obfuscated or obscure or difficult to understand in func =
lambda x: x**3 - 5*x when apparently most of the Python community find it
too complicated?

Whichever is "more readable" in the absolute sense, the "abused" lambda
expression above is within a gnat's whisker of the def equivalent,

def func(x):
return x**3 - 5*x

I honestly don't understand why it is supposed to be so hard to follow.

I can think of many function which should not be written with lambda, just
as some things shouldn't be written as list comps. But within the limits
of how much complexity you can reasonably include in a single expression,
I don't see why lambda puts people off.

I make it, eight mental tokens (not necessarily the same as Python tokens)
for the lambda versus nine for the def. A trivial difference. In my mind,
the tokens are:

func, =, lambda, x, :, x**3, -, 5*x

compared to:

def, func, (), x, :, return, x**3, -, 5*x

(Your mental parser may differ.)


> Also, it obfuscates tracebacks: all lambda expressions will identify in 
> tracebacks as , but if you define a function you can give it a 
> meaningful name.

Well there is that. If you have lots of lambdas assigned to names, I guess
debugging could be more difficult:

py> f = lambda x: 1.0/x
py> f(0)
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 1, in 
ZeroDivisionError: float division


py> def f(x):
... return 1.0/x
...
>>> f(0)
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 2, in f
ZeroDivisionError: float division

So far so good. But then:

py> g = f
py> del f
py> g(0)
Traceback (most recent call last):
  File "", line 1, in ?
  File "", line 2, in f
ZeroDivisionError: float division

(but we actually got the error by calling g, not f, and in fact f no
longer exists at the point we called g)


>> Why is it considered abuse of lambda to assign the 
>> functions to a name? Is it an abuse of lambda to do this?
>> 
>> D = {"one": lambda noun: noun,
>>  "two": lambda noun: noun + 's',
>>  "many": lambda noun: 'lots of ' + noun + 's' }
>> 
>> assert D["two"]("python") == "pythons"
>> 
>> 
> No, that is approaching a reasonable use of lambda, however I would still 
> be inclined to write it with functions. e.g.
> 
>def one(noun):
>return noun
> 
>def two(noun):
>return noun+'s'
> 
>def many(noun):
>return 'lots of %ss' % (noun,)
> 
>D = dict(one=one, two=two, many=many)

I find your version far more difficult to follow than mine.

Psychologically, I find that defs seem to carry significant mental weight
in a way that lambdas don't. Even though the lambda forms are
equivalent to the def forms, I find that the defs are more heavy-weight in
my conceptual map of the program than a lambda would be.

Put it this way: whenever I see a two-line def as above, I can't help
feeling that it is a waste of a def. ("Somebody went to all the trouble
to define a function for *that*?") Yet I would never think the same about
a lambda -- lambdas just feel like they should be light-weight. 

Am I just weird?



-- 
Steven.


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


Re: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Duncan Booth
Steven D'Aprano wrote:

> Put it this way: whenever I see a two-line def as above, I can't help
> feeling that it is a waste of a def. ("Somebody went to all the trouble
> to define a function for *that*?") Yet I would never think the same about
> a lambda -- lambdas just feel like they should be light-weight. 

Obviously we think differently there. I don't see why lambdas are any 
different than single expression functions. I certainly don't think of them 
as lighter weight; they take just as long to call; and they involve just as 
much stack setup/tear down. On the other hand I don't consider functions as 
heavyweight, I'm happy to define short helper functions anywhere I think it 
makes the code more expressive.

> Am I just weird?

No, just different[*]. There's nothing wrong with different.

[*] conclusion based entirely on your postings here. I have no evidence 
beyond that.

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


Re: (Win32 API) callback to Python, threading hiccups

2005-07-07 Thread Scott David Daniels
Francois De Serres wrote:
>PyGILState_STATE gil = PyGILState_Ensure();
>result = PyEval_CallObject(my_callback, arglist);   
>PyGILState_Release(gil);
>Py_DECREF(arglist);
>Py_DECREF(result);

I think this should be:
  PyGILState_STATE gil = PyGILState_Ensure();
  result = PyEval_CallObject(my_callback, arglist);
  Py_DECREF(arglist);
  Py_DECREF(result);
  PyGILState_Release(gil);

The DECREFs need to be protected, that is where storage is
recycled and such, and you still need Python's data structures
to do that kind of work.

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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Sion Arrowsmith
=?ISO-8859-2?Q?Pawe=B3?= Sakowski  <[EMAIL PROTECTED]> wrote:
 ll=[[1,2],[3,4,5],[6]]
 sum(ll,[])
>[1, 2, 3, 4, 5, 6]

That's a great argument for list.__add__ having the semantics of
extend rather than append 8-)

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Windows Cmd.exe Window

2005-07-07 Thread Giles Brown
Addendum - forgot to mention that the problem with checking the
extension of sys.argv[0] is that sys.argv[0] is not set until after
sitecustomize.py is run (and it needs to be in sitecustomize.py not an
imported module due to the top-level SyntaxError problem mentioned in
my other post).

Cheers again for your elegant solution.
Giles

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


Pattern question

2005-07-07 Thread cantabile
Hi,

I'm trying to write a small installer for a server. But this program
should be able to run in the future under heterogenous environments and
os (at least linux/windows). I mean, the install will be done either in
text mode or curses or gtk or tk, either in debian or windows 2000 and
so on...

The idea, at the moment, is as follows :

class Server:
def __init__(self, params = None):
self.params = params
def __getattr__(self, attr):
return self.params.get(attr, None)

class Installer:
 def __init__(self, gui = None):
self.gui =  gui
self.srv = None

def update(self, dict):
self.srv = Server(dict)

class Gui:
def __init__(self, installer = None):
self.installer = installer
def main():
## Some stuff here calling doIt() when the
## user is done with filling various fields

def doIt(self):
dict = {"param1":"qwerty", "param2":"uiop"}
self.installer.update(dict)

def main():
inst = Installer()
gui =  Gui(inst)
inst.gui = gui
inst.gui.main()

## Here will be the actual install method
## ...

## An example of accessing srv values:
print inst.srv.param1, inst.srv.param2

But, considering this code, I find the 3 first lines of my main() a bit
heavy. I have to inform inst that it has a 'gui', and Gui that it has an
'installer'. I was trying to implement something looking like (very
roughly) to the Observer pattern (so that the Gui would be totally
independant from the actual install process).
 I guess there is something wrong in my approach. Is there a better
pattern than this one for that kind of stuff ?

Tanks for your help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conditionally implementing __iter__ in new style classes

2005-07-07 Thread Bengt Richter
On Thu, 07 Jul 2005 09:51:42 +0200, Thomas Heller <[EMAIL PROTECTED]> wrote:

>[EMAIL PROTECTED] (Bengt Richter) writes:
>
>> On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller <[EMAIL PROTECTED]> wrote:
>>
>>>I'm trying to implement __iter__ on an abstract base class while I don't
>>>know whether subclasses support that or not.
>
>> Will a property or custom descriptor do what you want? E.g.
>>
>>  >>> class Base(object):
>>  ... def __getIter(self):
>>  ... if hasattr(self, "Iterator"):
>>  ... return self.Iterator
>>  ... raise AttributeError, name
>>  ... __iter__ = property(__getIter)
[...]
>
>Yep, that's exactly what I need - thanks.
>
BTW, I forgot to mention that you could use property as a decorator
in the above single-argument case:

 >>> class Base(object):
 ... @property
 ... def __iter__(self):
 ... if hasattr(self, "Iterator"):
 ... return self.Iterator
 ... raise AttributeError, name
 ...
 >>> class Concrete(Base):
 ... def Iterator(self):
 ... yield 1
 ... yield 2
 ... yield 3
 ...
 >>> iter(Base())
 Traceback (most recent call last):
   File "", line 1, in ?
 TypeError: iteration over non-sequence
 >>> iter(Concrete())
 
 >>> list(iter(Concrete()))
 [1, 2, 3]

Hope there isn't a gotcha for your use case in the way an instance attribute
of the same name is allowed. A custom descriptor could eliminate that.

 >>> inst = Concrete()
 >>> list(iter(inst))
 [1, 2, 3]
 >>> inst.__init__ = 'abc'
 >>> list(iter(inst))
 [1, 2, 3]
 >>> inst.__init__
 'abc'



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


Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

2005-07-07 Thread Ron Adam
Reinhold Birkenfeld wrote:
> Ron Adam wrote:
> 
> 
>>Given the statement:
>>
>>a = None
>>
>>And the following are all true:
>>
>>  a == None
> 
> 
> Okay.
> 
> 
>>(a) == (None)
> 
> 
> Okay.
> 
> 
>>(a) == ()
> 
> 
> Whoops! a (which is None) is equal to the empty tuple (which is not None)?

It's not an empty tuple, it's an empty parenthesis.  Using tuples it 
would be.

(a,) == (,)

which would be the same as:

(,) == (,)

>>(None) == ()
>>
>>Then this "conceptual" comparison should also be true:
>>
>>if (None):  ==  if ():
>>if (): == if:
> 
> 
> I can't really see any coherent concept here.
> 
> Reinhold

It would work out that.

if: == if:

Does that help?

Cheers,
Ron



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


Re: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Bengt Richter
On 7 Jul 2005 15:46:23 GMT, Duncan Booth <[EMAIL PROTECTED]> wrote:

>Steven D'Aprano wrote:
>
>> Put it this way: whenever I see a two-line def as above, I can't help
>> feeling that it is a waste of a def. ("Somebody went to all the trouble
>> to define a function for *that*?") Yet I would never think the same about
>> a lambda -- lambdas just feel like they should be light-weight. 
>
>Obviously we think differently there. I don't see why lambdas are any 
>different than single expression functions. I certainly don't think of them 
>as lighter weight; they take just as long to call; and they involve just as 
>much stack setup/tear down. On the other hand I don't consider functions as 
>heavyweight, I'm happy to define short helper functions anywhere I think it 
>makes the code more expressive.
>
>> Am I just weird?
>
>No, just different[*]. There's nothing wrong with different.
>
>[*] conclusion based entirely on your postings here. I have no evidence 
>beyond that.
>
I think def is a form of assignment, with the target binding name
specified inside the expression syntax instead of to the left of an '=' as 
usual. I.e.,

def f(args): suite

is like

f = def(args): suite

except that I can't use an arbitrary left-hand side in the assignment, such as

MyClass.method = def(self, args): suite
or
   somedict['foo'] = def(self, args): suite

Personally, I think def(args): suite ought to be allowed as an expression that 
you could
put in parentheses like any other expression if you need/want to write it with 
multiple lines.
Obviously this could both replace and expand the functionality of lambda ;-)

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


Re: flatten(), [was Re: map/filter/reduce/lambda opinions ...]

2005-07-07 Thread Tom Anderson

On Thu, 7 Jul 2005, Ron Adam wrote:


Stian Søiland wrote:

> Or what about a recursive generator?


That's the sort of thing i like to see!

Ok, lets see...  I found a few problems with the testing (and corrected 
it) so the scores have changed.  My sort in place routines were cheating 
because the lists weren't reset between runs so it had the advantage 
after the first time though of sorting already sorted list.


Aaagh, of course!

And Tom's recursive no copy had a bug which kept a reference to one of 
it's arguments so it's output was doubling the list.


Oops. I really should have written tests as well as benchmarks.

And the hasattr function was slowing everyone down, so I inlined it for 
everyone who used it. Using a 1000 item list and starting with a flat 
list and increasing the depth (unflatten) to shallow, medium, and deep. 
(but not so deep to cause recursion errors.)


I wrote a new and improved test harness myself, but left my laptop at 
work, and haven't been in today due to the bombs :(. I ran tests out to 
100 000 elements, and your implementation was still faster, although not 
by a lot - but then i hadn't found the bugs you had, so it's all moot.



And the winners are...

Stians flatten generator is nearly tied with Tom's recursive zerocopy. 
My nonrecursive inplace is faster for very shallow lists, but Tom's 
quickly over takes it.  I was able to improve my nonrecursive copy 
flatten a bit, but not enough to matter.


I also came up with an improvement to my version that should cut down on 
recursive calls - a sort of recursion unrolling. I doubt it wouldd make 
much difference, though.


So Tom's recursive zerocopy is the overall winner with Stian's flatten 
generator close behind and just barely winning out in the very deep 
catagory.


\o/


But they're all respectable times so everyone wins. ;-)


Everyone shall have medals!

tom

--
They travel the world in their ice cream van ...-- 
http://mail.python.org/mailman/listinfo/python-list

Re: latex/bibtex python paper?

2005-07-07 Thread ansobol
Kurt,

Try  and search
this site (the famous UK TeX FAQ) at
 for
other info.

You might also ask this question at the comp.text.tex group (which, in
my experience, is as nice as this one).

HTH
Andrei

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


Re: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Ron Adam
Steven D'Aprano wrote:

> On Thu, 07 Jul 2005 09:36:24 +, Duncan Booth wrote:
> 
> 
>>Steven D'Aprano wrote:
>>
>>>This is something I've never understood. Why is it bad 
>>>form to assign an "anonymous function" (an object) to a 
>>>name?
>>
>>Because it obfuscates your code for no benefit. You should avoid making it 
>>hard for others to read your code (and 'others' includes yourself in the 
>>future).

Use a descriptive name like this?

def get_the_cube_of_x_and_then_subtract_five_multiplied_by_x(x):
  x**3 - 5*x

I think I like the lambda version here.  ;-)

It would probably have a name which refers to the context in which it's 
used, but sometimes the math expression it self is also the most readable.



> Put it this way: whenever I see a two-line def as above, I can't help
> feeling that it is a waste of a def. ("Somebody went to all the trouble
> to define a function for *that*?") Yet I would never think the same about
> a lambda -- lambdas just feel like they should be light-weight. 

In the case of an interface module you might have a lot of two like 
def's that simply change the name and argument format so several modules 
can use it and have a standard consistent or simplified interface.

The lambda may be perfectly fine for that.  But why not use def?

func_x = lambda x: (someother_func_x(x,'value'))

def func_x(x): return someother_func_x(x,'value')

There's both nearly identical, but the def is understandable to 
beginners and advanced python programs.


Cheers,
Ron


> Am I just weird?

Aren't we all?   ;-)

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


method for Exception base class to raise the exception in an expression?

2005-07-07 Thread Bengt Richter
Sometimes it could be handy, e.g., cutting short iteration:

 >>> def raisex(self, *args):
 ... raise self.__class__(self, *args)
 ...
 >>> Exception.raisex = raisex
 >>> list(i for i in xrange(20) if i<10 or StopIteration().raisex())
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> list(i for i in xrange(20) if i<15 or StopIteration().raisex())
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
 >>> list(i for i in xrange(20) if i<25 or StopIteration().raisex())
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

a class method could be nicer once we have Exception as a new-style class.

Just a thought.

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


Re: precision problems in base conversion of rational numbers

2005-07-07 Thread [EMAIL PROTECTED]


Raymond Hettinger wrote:
> > > For a simple example, convert both 10247448370872321 and
> > > 10247448370872319 from base ten to 4 digits of hex.  The calculations
> > > need to be carried out to 15 places of hex (or 17 places of decimal)
> > > just to determine whether the fourth hex digit is a 7 or 8:
> > >
> > > >>> hex(10247448370872321)
> > > '0x246801L'
> > > >>> hex(10247448370872319)
> > > '0x2467ffL'
> >
> > I don't understand your simple example.
> >
> > log(10)/log(16) = 0.83048202372184058696757985737235
> >
> > Multiplying by the number of decimal digits (17) gives
> >
> > 14.11819440327128997844885757533
> >
> > Rounding up to an integer digit count, we need need 15 hex digits.
> > Isn't that exactly what you concluded? Where does that 4 hex digit
> > stuff come from?
>
> It is part of the OP's problem spec.  Given a number x (which may be a
> decimal, float, long integer, or rational), a base b, and a desired
> precision p, compute the conversion to p-digits:
>
>   >>> convert(x=10247448370872319L, b=16, p=4)
>   '246800'

But you haven't explained why you are using p=4. The OP's problem
is that he's doing convert(x=10247448370872319L, b=16, p=17).
So of course it's going to be wrong because base 16 numbers are
bigger than base 10 numbers. By trying to use the same precision
with different bases, he's asking for more precision in the base 17
number than what exists in the base 10 number.

>
> He wanted to know what decimal precision he needed to set to make the
> conversion accurate to the last place.  The required precision for
> intermediate calculations depends on how close x is to a representable
> value in the target base.  The 16 digits are not known a priori since x
> may be a rational, float, or decimal.  For instance, an internal
> precision of 17 digits would also be needed for other nearby values of
> x:
>
>   >>> convert(x=Decimal("10247448370872319.1", b=16, p=4)
>   '246800'

Now your base 10 number has 26 digits. So shouldn't your convert be
using p=22?

>
> The number 17 does not just pop-out of a simple logarithm.

It most certainly does

>>> print floor(math.log10(10247448370872319)) + 1
17.0


> How many
> internal digits of precision do you need for convert(math.pi, b=16,
> p=5)?

I think I would need 7.

Because
>>> print math.log(16)/math.log(10)*5
6.02059991328


>>> from gmpy import *
>>> import math
>>> print math.pi
3.14159265359

Using math.pi

>>> print fdigits(math.pi,16,5)
[EMAIL PROTECTED]

Using only seven digits

>>> print fdigits(mpf("3.141593"),16,5)
[EMAIL PROTECTED]

I don't see any problem.

> If the result falls closely between reprentable values, the OP
> may need to set his "magic number" to something larger than you would
> have predicted.
>
> If you want insight into why the OP's problem statement is deeper than
> it appears, then ponder the mystery of why the following returns False:
>
>   >>> x = 554459760520464551937111727196883414687442277344893869152167
>   >>> float(x) == float(str(x))
>   False

No big mystery. Isn't that why they added the Decimal module?

>
> Hint, the two different underlying routines are trying to compute,
> convert(x, b=2, p=53), without the benefit of arbitrary precision
> arithmetic.

Yep, sure is nice to have that.

>>> x = mpz(554459760520464551937111727196883414687442277344893869152167)
>>> float(x)==float(str(x))
True


> 
> 
> Raymond

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


Re: flatten()

2005-07-07 Thread Björn Lindström
Tom Anderson <[EMAIL PROTECTED]> writes:

> Stian Søiland wrote:
>
> > Or what about a recursive generator?
>
> That's the sort of thing i like to see!

That can be a neat method. It's a pretty verbose way to do flatten(),
but it's a good example:

def flatten(l):
for e in l:
if isinstance(e, list):
for f in flatten(e):
yield f
else:
yield e

for x in flatten([0, [1, 2, [3, 4], 5], 6, 7]):
whatever()

--
Björn Lindström <[EMAIL PROTECTED]>
Student of computational linguistics, Uppsala University, Sweden
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how to change a script while it is running

2005-07-07 Thread Do Re Mi chel La Si Do
Hi !

Try :


def ff(a):
print a*2

ff(111)

exec('''def ff(a):
print a*3
''',globals(),globals())

ff(111)



@-salutations

Michel Claveau





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


Re: Deleting variables [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Tom Anderson
On Thu, 7 Jul 2005, Steven D'Aprano wrote:

> On Wed, 06 Jul 2005 14:28:55 +0100, Tom Anderson wrote:
>
>>> del -> delete
>>
>> How about just getting rid of del? Removal from collections could be done
>> with a method call,
>
> Which would be called object.del() I presume.

That would be fine.

> And that opens a big can of worms.
>
> Suppose we have a list L = [4, 3, 2, 1, 0], what should L.del(1) do?

Delete the item at index 1, just as del L[1] would.

> It looks like it should result in L becoming [4, 3, 2, 0].

Why? I guess if you hadn't read the documentation and were just calling 
methods at random, you might, but i can't think of any other case.

> An easy mistake to make, if you forget that the argument is (presumably) 
> an index.

Not the kind of thing people tend to forget! There is the problem that 
people might get del and remove mixed up; i didn't actually realise there 
was a remove method on lists until i looked just now.

> You could make it clear by insisting on L.del[1] but that requires a big 
> change in Python's syntax.

It would, so i wouldn't dream of insisting on it.

> What should L.del() do, with no arguments? Raise an error?

Er, exactly the same as calling any other method with a wrong-length 
argument list - a TypeError, i should think.

> Now, you have something like this:
>
> class thing:
>pass
> obj = thing()
> obj.alpha = [4, 3, 2, 1, 0]
> obj.beta = 5
>
> Python's object model suggests that obj.alpha.del() should call alpha's 
> del method, in the same way that obj.alpha.append() would call alpha's 
> append method.

Exactly so.

> So how do you delete obj.alpha? obj.del("alpha") might work. But what if 
> obj itself is a mapping, with a key "alpha" as well as an attribute 
> alpha. Which one should obj.del("alpha") delete?

I don't think objects should have a del method by default. I'd suggest a 
delattr or removeattr builtin, working along the lines of getattr and 
setattr, for this task.

> Now, if you said that L.del() should raise an exception earlier, what 
> about obj.beta.del()?

Unless int has a del method, that would be an exception - an 
AttributeError, to be precise.

> Presumably every object automatically has a del method,

I'd say no, but for the sake of argument, let's say it does.

> so you don't have to program a del method yourself. obj.del is a method 
> object. So it has a del method. (Yes, sometimes you want to delete 
> methods. Functions are first class objects in Python.) Which has a del 
> method. Which has a del method.

Right.

> What should obj.del.del.del.del.del.del.del.del.del() do?

Raise a TypeError, since you haven't passed any parameters.

As for obj.del.del.del.del.del.del.del.del.del("del"), that's an 
interesting one - it comes down to the question of whether those del 
methods are the same object or not. I'd say not: for two objects a and b 
of the same class, a.foo and b.foo are considered different objects in 
python, and that applies here.

>> and i'm not convinced that deleting variables is something we really 
>> need to be able to do (most other languages manage without it).
>
> Most other languages don't have namespaces that can get polluted, or
> on-the-fly creation of variables. Most other languages don't consider
> variables to be simply attributes of a module object.

How much is that really used? And how many of those cases wouldn't be 
covered by a delattr builtin?

> And most other languages don't allow you to run interactive sessions 
> where it is easy to mistakenly make variables you don't want.
>
> py> x = 1
> py> u = x+2  # oops, typo, meant y not u
> py> del u  # prevent confusion in the programmer's mind
>
> It is also useful sometimes to delete a module object from the top level 
> namespace before re-importing it, rather than merely reloading it. That 
> requires being able to delete a variable.

That's a very strong use case. However, it would be straightforward to 
make variable deletion an interpreter thing rather than a language thing.

> In summary: del being a keyword works. del() being an object method is 
> unclear, confusing and complicated.

Only if you give it the bizarre semantics you use above!

I think having del as a keyword is actually unhelpful, since it's 
overloaded to do two quite different things - remove items from lists and 
dicts, and expunge attributes from namespaces. Far better to do let lists 
and dicts expose methods to let themselves be manipulated, and to play 
with attributes through a uniform troika of {get, set, del}attr builtins.

tom

-- 
They travel the world in their ice cream van ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you program in Python?

2005-07-07 Thread Jorgen Grahn
On Thu, 07 Jul 2005 18:10:44 +1000, Gregory Bond <[EMAIL PROTECTED]> wrote:
> Jorgen Grahn wrote:
>
>> Emacs and vim are almost always installed, or trivially installable. All I
>> need to remember is to bring my emacs config file.
>
> And, fortunately, USB pen drives are now big enough to hold it!

Hey, it's not fair to make fun of emacs now that I've mentioned vim
favourably so many times ;-)

Seriously, nothing about emacs seems big or slow today. It has been
outbloated by pretty much everything else. Who could have imagined /that/
ten years ago?

/Jorgen
(And just in case this thread deteriorates into a silly emacs-vs-vi
argument, I hereby declare myself out of the game.)

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


print values from Py_BuildValue

2005-07-07 Thread [EMAIL PROTECTED]
Hello,

How do i print values returned by Py_BuildValue in Linux?

PyObject *obj = Py_BuildValue("{s:i}", "Status", status);

I need to print the Status value here

-Thanks,
Ashton

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


Re: question about introspection using inspect module

2005-07-07 Thread Fernando Perez
Benjamin Rutt wrote:

> I'm trying to learn about introspection in Python.  my ultimate goal
> is to be able to build a module "text database" of all modules that
> are in the sys.path, by discovering all candidate modules (I've
> already done that), importing all of them, and then introspecting on
> each module to discover its functions, globals and classes.  But for
> now I am having a problem with the latter.

I certainly don't want to discourage you from learning about python
introspection, it's one of the most fun aspects of the language.  But just as
an FYI, the pydoc system already does much of what you have in mind, at least
if I'm reading your description correctly:

planck[/tmp]> pydoc -p 12345
pydoc server ready at http://localhost:12345/


Just point your favorite webbrowser to that URL (use any port number you want,
and which isn't already in use).

Cheers,

f

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


Re: Use cases for del

2005-07-07 Thread Ron Adam
Grant Edwards wrote:

> On 2005-07-07, Ron Adam <[EMAIL PROTECTED]> wrote:

>>It would be a way to set an argument as being optional without
>>actually assigning a value to it.
>>
>>So it would still work like you expect even though v is not
>>bound to anything.  Like I said the bigger problem is that
>>globals will be visible and that would create a conflict.
>>Setting a value to None in a function hides globals of the
>>same name.  That wouldn't happen if None unbound names as del
>>does.
> 
> Good point.  I hadn't thought of that.

The easiest way to fix that is to create a Nil or Null object as a 
replacement for the current None object.


>>>I find it more obvious to set the name to None during the
>>>periods that it isn't valid than to delete it and check for a
>>>NameError when I want to know if the value is usable or not.
>>
>>You would still be able to do that explicitly and it probably would be a 
>>good idea when you aren't sure if a name is left over from something else.
>>
>>If a name is None, it means it's available and unassigned, so
>>you don't have to check for a NameError.
> 
> 
> How would you spell "if a name is None"?

How about:

if name is None: name = something

Making None the same as undefined wouldn't change this.  I think the 
parser would need to be a little smarter where None is concerned in 
order to be able to handle it in bool expressions,  and catch improper 
name = undefined assignments.

But it might not change things as much as you think.


> Personally, I think the spellings
> 
>del name
>if 'name' in locals()
> 
> is much more explicit/obvious than
> 
>name = None
>name is None   

This would be
  name = None # remove it from locals()
  if name is None: dosomething# if it's not in locals()

No need to check locals or globals.  That's one of the plus's I think.


Since we can already assign a value to any name without first 
initializing it,  this just allows us to use it in a some expressions 
without also first initializing it.  It would still give an error if we 
tried to use it in "any" operation.  Just like the present None.


> I expect the "=" operator to bind a name to a value.  Having it
> do something completely different some of the time seems a bit
> unpythonic.

But you are assigning it a value. Instead of having a Name assigned to a 
None object, the name is just removed from name space to do the same 
thing and you save some memory in the process.



How about keeping None as it is as a place holder object, and having a 
keyword called "undefined" instead.

x = 3
x = undefined   # delete x from name space
if x is not undefined: print x

if an undefined name is used with any operator, it could give a 
'UndefinedName' error.

This would be more compatible with the current python language.

Cheers,
Ron

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


Re: Use cases for del

2005-07-07 Thread Ron Adam
Steven D'Aprano wrote:

> Ron Adam wrote:
> 
>> Why would you want to use None as an integer value?
>>
>> If a value isn't established yet, then do you need the name defined? 
>> Wouldn't it be better to wait until you need the name then give it a 
>> value?
> 
> 
> Er, maybe I'm misunderstanding something here, but surely the most 
> obvious case is for default and special function arguments:
> 
> def count_records(record_obj, start=0, end=None):
> if end == None:
> end = len(record_obj)
> if start == None:  # this is not the default!
> # start at the current position
> start = record_obj.current
> n = 0
> for rec in record_obj.data[start:end]:
> if not rec.isblank():
> n += 1
> return n
> 
> which you call with:
> 
> # current position to end
> count_records(myRecords, None)
> # start to end
> count_records(myRecords)
> # start to current position
> count_records(myRecords, end=myRecords.current)


You have three possible outcomes,
count all
count range
count using current index
count range from beginning to current
count range from current to end


The most consistent way to do this would be:


def count_records(record_obj, start=0, end=len(record_obj)):
 n = 0
 for rec in record_obj.data[start:end]:
 if not rec.isblank():
 n += 1
 return n


# current position to end
count_records(myRecords, myRecords.current)

# start to end
count_records(myRecords)

# start to current position
count_records(myRecords, end=myRecords.current)


Cheers,
Ron



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


Re: Use cases for del

2005-07-07 Thread Dieter Maurer
Daniel Dittmar <[EMAIL PROTECTED]> writes on Wed, 06 Jul 2005 16:12:46 +0200:
> Peter Hansen wrote:
> > Arguing the case for del: how would I, in doing automated testing,
> > ensure that I've returned everything to a "clean" starting point in
> > all cases if I can't delete variables?  Sometimes a global is the
> > simplest way to do something... how do I delete a global if not with
> > "del"?
> 
> 
> globals ().__delitem__ (varname)
> 
> except that the method would probably be called delete.

You now have a uniform way to remove an object from a namespace.

Why would you want to give each namespace its own method to
remove objects from it?

Can you imagine how much code you would break (would your proposal
to remove "del" got accepted)?


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


Re: Conditionally implementing __iter__ in new style classes

2005-07-07 Thread Dieter Maurer
Thomas Heller <[EMAIL PROTECTED]> writes on Wed, 06 Jul 2005 18:07:10 +0200:
> Thomas Heller <[EMAIL PROTECTED]> writes:
> ...
> > class Base:
> > def __getattr__(self, name):
> > if name == "__iter__" and hasattr(self, "Iterator"):
> > return self.Iterator
> > raise AttributeError, name
> >
> > class Concrete(Base):
> > def Iterator(self):
> > yield 1
> ...
> > If, however, I make Base a newstyle class, this will not work any
> > longer.  __getattr__ is never called for "__iter__" (neither is
> > __getattribute__, btw).  Probably this has to do with data descriptors
> > and non-data descriptors, but I'm too tired at the moment to think
> > further about this.
> >
> > Is there any way I could make the above code work with new style
> > classes?
> 
> I forgot to mention this: The Base class also implements a __getitem__
> method which should be used for iteration if the .Iterator method in the
> subclass is not available.  So it seems impossible to raise an exception
> in the __iter__ method if .Iterator is not found - __iter__ MUST return
> an iterator if present.

Then, it should return an interator (a new object) that uses
the "__getitem__" method to iterate.


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


Python Module Exposure

2005-07-07 Thread Jacob Page
I have created what I think may be a useful Python module, but I'd like 
to share it with the Python community to get feedback, i.e. if it's 
Pythonic.  If it's considered useful by Pythonistas, I'll see about 
hosting it on Sourceforge or something like that.  Is this a good forum 
for exposing modules to the public, or is there somewhere 
more-acceptable?  Does this newsgroup find attachments acceptable?

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


Re: ANN: python-constraint 1.0

2005-07-07 Thread Alexandre Fayolle
On Thu, Jul 07, 2005 at 03:40:10AM -0300, Gustavo Niemeyer wrote:
> 
> Overview
> 
> 
> **python-constraint** [1]_ is a Python module offering solvers for
> Constraint Solving Problems (CSPs) over finite domains in simple
> and pure Python. CSP is class of problems which may be represented
> in terms of variables (`a`, `b`, ...), domains (`a in [1, 2, 3]`, ...),
> and constraints (`a < b`, ...).
> 
> .. [1] http://codespeak.net/~niemeyer/constraint/

People interested in CSP and python may also want to check Logilab's
constraint module which has been available from some time at:

http://www.logilab.org/projects/constraint/

Gustavo, maybe we should coordinate and merge our efforts?

-- 
Alexandre Fayolle  LOGILAB, Paris (France).
http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org


signature.asc
Description: Digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Why anonymity? [was Re: map/filter/reduce/lambda opinions and background unscientific mini-survey]

2005-07-07 Thread Daniel Schüle
> Am I just weird?

I feel the same way about where to use lambda's and where *not*
I come from C and C++ background and defining a function at the top 
level (no nested functions) would always require good reasons

function name has to be remembered, to put it in other words it has to 
be added in a mental list of available function
and writing a 2 liner function would only cause call overhead
(if not inlined) this may be the reason why "def" feels to me to have 
more weight as "lambda"
usually you define lambda and forget it, no wasted time to find proper 
name, which may also pollute the namespace
I find it more clear solution, it's concise

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


Re: Favorite non-python language trick?

2005-07-07 Thread Robert Kern
Edvard Majakari wrote:
> Simon Brunning <[EMAIL PROTECTED]> writes:
> 
>>http://wiki.python.org/moin/PythonDecoratorLibrary?#head-de01988728ccdec415708f10928cc6feb022e7bb
> 
> Neat.
> 
> I guess about 75% about programming-related things classified as neat-o or
> "convenient!" are already implemented by some Pythonista(s). Spoils all the
> fun for reinventing the wheel, doesn't it. :)

Doesn't seem to stop most Pythonistas from trying, though.  :-)

-- 
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: Python Module Exposure

2005-07-07 Thread Robert Kern
Jacob Page wrote:
> I have created what I think may be a useful Python module, but I'd like 
> to share it with the Python community to get feedback, i.e. if it's 
> Pythonic.  If it's considered useful by Pythonistas, I'll see about 
> hosting it on Sourceforge or something like that.  Is this a good forum 
> for exposing modules to the public, or is there somewhere 
> more-acceptable?  Does this newsgroup find attachments acceptable?

No. Please put files somewhere on the web and post a URL. This would be 
a good forum to informally announce and discuss your module. Formal 
announcements once you, e.g. put it on SF should go to c.l.py.announce .

-- 
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: latex/bibtex python paper?

2005-07-07 Thread Jules Dubois
On Wednesday 06 July 2005 09:28, [EMAIL PROTECTED] <[EMAIL PROTECTED]>
(<[EMAIL PROTECTED]>) wrote:

> Hi All,
> 
> Does anyone have a good template that I might use for writing a python
> paper in latex/bibtex?  [...]
> 
> When I cite these, I get something like this (Foundation[2005]).

Questions like this are better asked in comp.text.tex, where they are
on-topic.

There is a fine TeX/LaTeX/etc. FAQ at:

  http://www.tex.ac.uk/cgi-bin/texfaq2html

Finally, here are some sample bibtex results:

  http://www.cs.stir.ac.uk/~kjt/software/latex/showbst.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conditionally implementing __iter__ in new style classes

2005-07-07 Thread Thomas Heller
[EMAIL PROTECTED] (Bengt Richter) writes:

> On Thu, 07 Jul 2005 09:51:42 +0200, Thomas Heller <[EMAIL PROTECTED]> wrote:
>
>>[EMAIL PROTECTED] (Bengt Richter) writes:
>>
>>> On Wed, 06 Jul 2005 17:57:42 +0200, Thomas Heller <[EMAIL PROTECTED]> wrote:
>>>
I'm trying to implement __iter__ on an abstract base class while I don't
know whether subclasses support that or not.
>>
>>> Will a property or custom descriptor do what you want? E.g.
>>>
>>>  >>> class Base(object):
>>>  ... def __getIter(self):
>>>  ... if hasattr(self, "Iterator"):
>>>  ... return self.Iterator
>>>  ... raise AttributeError, name
>>>  ... __iter__ = property(__getIter)
> [...]
>>
>>Yep, that's exactly what I need - thanks.
>>
> BTW, I forgot to mention that you could use property as a decorator
> in the above single-argument case:
>
>  >>> class Base(object):
>  ... @property
>  ... def __iter__(self):
>  ... if hasattr(self, "Iterator"):
>  ... return self.Iterator
>  ... raise AttributeError, name

Of course.  I didn't spot this, but I cannot use this anyway for 2.3
compatibility.

>  ...
>  >>> class Concrete(Base):
>  ... def Iterator(self):
>  ... yield 1
>  ... yield 2
>  ... yield 3
>  ...
>  >>> iter(Base())
>  Traceback (most recent call last):
>File "", line 1, in ?
>  TypeError: iteration over non-sequence
>  >>> iter(Concrete())
>  
>  >>> list(iter(Concrete()))
>  [1, 2, 3]
>
> Hope there isn't a gotcha for your use case in the way an instance attribute
> of the same name is allowed. A custom descriptor could eliminate that.
>
>  >>> inst = Concrete()
>  >>> list(iter(inst))
>  [1, 2, 3]
>  >>> inst.__init__ = 'abc'
>  >>> list(iter(inst))
>  [1, 2, 3]
>  >>> inst.__init__
>  'abc'

I don't understand what you mean here.  A __iter__ instance attribute?

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


Re: Lisp development with macros faster than Python development?..

2005-07-07 Thread Terry Reedy

"jayessay" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> 1. Someone recently remarked that good Lisp macros are basically
>   executable pseudo code.  I think that is pretty much exactly right
>   and is a pretty good "sound bite" distillation of what it is all
>   about.

Several years ago  I remarked that Python reads like executable pseudocode. 
I still think that that is pretty much right.

Googling, I discovered that the creators of some thing I had never heard of 
said the same thing about *their* language a couple of years ago.  I wish 
web pages, like newgroup posts, were dated so one could better trace the 
history of such usages.

Terry J. Reedy 



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


Re: Thoughts on Guido's ITC audio interview

2005-07-07 Thread Ville Vainio
> "Fabio" == Fabio Zadrozny <[EMAIL PROTECTED]> writes:

>> I agree about the project management part. Though I would still love
>> to use Eclipse instead, if it only was supported for my line of work
>> :-/.

Fabio> What line of work is not supported in eclipse?

C++ programming for Symbian OS. Editing the C++ code works, debugging
doesn't, at least yet.

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lisp development with macros faster than Python development?..

2005-07-07 Thread Terry Reedy

"Antoon Pardon" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I'll clarify. A lot of the time I hear arguments against
> features that boils down to.
>
> 1) I don't need it.
>
> 2) Having the feature will make my job more difficult.
>
> 3) I don't understand the merrits of the feature or I
>   have difficulty understanding what it does when I
>   encounter it.
>
> IMO these are arguments if followed sufficiently will lead to
> a language that is only usefull for mediocre programmers.

True.  But these arguments did not stop expert-level features like 
metaclasses, decorators, and (in 2.5) context-management blocks 
(with-blocks).

TJR



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


Re: Lisp development with macros faster than Python development?..

2005-07-07 Thread Robert Kern
Terry Reedy wrote:
> "jayessay" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
>>1. Someone recently remarked that good Lisp macros are basically
>>  executable pseudo code.  I think that is pretty much exactly right
>>  and is a pretty good "sound bite" distillation of what it is all
>>  about.
> 
> Several years ago  I remarked that Python reads like executable pseudocode. 
> I still think that that is pretty much right.
> 
> Googling, I discovered that the creators of some thing I had never heard of 
> said the same thing about *their* language a couple of years ago.  I wish 
> web pages, like newgroup posts, were dated so one could better trace the 
> history of such usages.

Trawling through http://web.archive.org might help.

-- 
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: Why anonymity? [was Re: map/filter/reduce/lambda opinions andbackground unscientific mini-survey]

2005-07-07 Thread Terry Reedy
The difference in readability between

func = lambda x: x**3 - 5*x

def func(x):
return x**3 - 5*x

def func(x): return x**3 - 5*x

is obviously a matter of personal vision.

The fuctional difference (and, I believe, the only difference) is that the 
def form attaches the specific name 'func' to the function object as its 
func_name attribute while the lambda form attaches the generic 'name' 
''.   This makes tracebacks, for instance, less informative.

The reason some think the name=lambda form an abuse is that it is a second 
way to do almost the same thing (with the functional difference being a 
negative) while ignoring the intended purpose of lambda's presence in the 
language.  (But I will not argue this either way.)

Terry J. Reedy





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


Calculating average time

2005-07-07 Thread GregM
Hi,
I'm hoping that someone can point me in the right direction with this.
What I would like to do is calculate the average time it takes to load
a page. I've been searching the net and reading lots but I haven't
found anything that helps too much. I'm testing our web site and hiting
+6000 urls per test. Here is a subset of what I'm doing.

import IEC
#IE controller from http://www.mayukhbose.com/python/IEC/index.php
from win32com.client import Dispatch
import time
import datetime
from sys import exc_info, stdout, argv, exit
failedlinks = []
links = open(testfile).readlines()
totalNumberTests = len(links)
ie = IEC.IEController()
start = datetime.datetime.today()
# asctime() returns a human readable time stamp whereas time() doesn't
startTimeStr = time.asctime()
for link in links:
start = datetime.datetime.today()
ie.Navigate(link)
end = datetime.datetime.today()
pagetext = ie.GetDocumentText()
#check the returned web page for some things
if not (re.search(searchterm, pagetext):
 failedlinks.append(link)
ie.CloseWindow()
finised = datetime.datetime.today()
finishedTimeStr = time.asctime()
# then I print out results, times and etc.

So:
1. Is there a better time function to use?

2. To calculate the average times do I need to split up min, sec, and
msec and then just do a standard average calculation or is there a
better way?

3. is there a more efficient way to do this?

4. kind of OT but is there any control like this for Mozilla or
firefox?

This is not intended to be any sort of load tester just a url
validation and page check.

Thanks in advance.
Greg.

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


Re: Python Module Exposure

2005-07-07 Thread Jacob Page
Robert Kern wrote:

> Jacob Page wrote:
> 
>> I have created what I think may be a useful Python module, but I'd 
>> like to share it with the Python community to get feedback, i.e. if 
>> it's Pythonic.  If it's considered useful by Pythonistas, I'll see 
>> about hosting it on Sourceforge or something like that.  Is this a 
>> good forum for exposing modules to the public, or is there somewhere 
>> more-acceptable?  Does this newsgroup find attachments acceptable?
> 
> No. Please put files somewhere on the web and post a URL. This would be 
> a good forum to informally announce and discuss your module. Formal 
> announcements once you, e.g. put it on SF should go to c.l.py.announce .

Thanks for the information, Robert.  Anyway, here's my informal 
announcement:

The iset module is a pure Python module that provides the ISet class and 
some helper functions for creating them. Unlike Python sets, which are 
sets of discrete values, an ISet is a set of intervals. An ISet could, 
for example, stand for all values less than 0, all values from 2 up to, 
but not including 62, or all values not equal to zero. ISets can also 
pertain to non-numeric values.

ISets can be used in much the same way as sets. They can be or'ed, 
and'ed, xor'ed, added, subtracted, and inversed. Membership testing is 
done the same as with a set. The documentation has some examples of how 
to create and use ISets.

The iset module is for Python 2.4 or later.

I am seeking feedback from programmers and mathematicians on how to 
possibly make this module more user-friendly, better-named, 
better-documented, better-tested, and more Pythonic.  Then, if this 
module is considered acceptable by the community, I'll create a more 
permanent home for this project.

To download the iset module and view its pydoc-generated documentation, 
please visit http://members.cox.net/apoco/iset/.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: map/filter/reduce/lambda opinions and background unscientificmini-survey

2005-07-07 Thread Terry Reedy

"Pawe³ Sakowski" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Tom Anderson wrote:
> def flatten(ll):
>  return reduce(lambda a, l: a.extend(l), ll, [])
>
> How would one do that as a list comp, by the way? I'm really not very 
> good
> with them yet.

Not really a list-comprehension based solution, but I think what you want 
is

>>> ll=[[1,2],[3,4,5],[6]]
>>> sum(ll,[])
[1, 2, 3, 4, 5, 6]

Unless sum knows to typecheck input items and special-case lists and use 
list.extend rather than list+list, this turns an O(n) operation into an 
O(n**2) operation.  Sum is meant for numbers.

Terry J. Reedy



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

Re: Calculating average time

2005-07-07 Thread Skip Montanaro

greg> 1. Is there a better time function to use?

For this particular scenario I think time.time() is probably what you want:

cumulative = 0.0
n = 0
for link in links:
t = time.time()
ie.Navigate(link)
cumulative += time.time() - t
n += 1

print "average page load time:", cumulative/n, "seconds"

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


Re: ANN: python-constraint 1.0

2005-07-07 Thread Gustavo Niemeyer
Hello Alexandre,

> People interested in CSP and python may also want to check Logilab's
> constraint module which has been available from some time at:
> 
> http://www.logilab.org/projects/constraint/

Indeed! And please send us some notes comparing both. :-)

The AIMA book inspired me to write that module. IIRC, there's
also some kind of constraint code in Python by one of the book
authors (Peter Norvig). For those who are interested, chapter 5,
which talks about CSPs, may be found in the web site.

> Gustavo, maybe we should coordinate and merge our efforts?

Probably. I confess that even though I'm using CSP logic on
other real world projects, I wrote that module completely for
fun, and was not really caring if I was reinventing the wheel
or not.

> Alexandre Fayolle  LOGILAB, Paris (France).

I'm currently in Paris, btw.

-- 
Gustavo Niemeyer
http://niemeyer.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Module Exposure

2005-07-07 Thread Rocco Moretti
Robert Kern wrote:
> Jacob Page wrote:
> 
>> Does this newsgroup find attachments acceptable?
> 
> No. Please put files somewhere on the web and post a URL. This would be 
> a good forum to informally announce and discuss your module. 

To add to what Robert said, keep in mind this newsgroup is also mirrored 
to a mailing list, so posting anything but example code snippets would 
quickly fill up people's inboxes.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >