Re: Suggesion for an undergrad final year project in Python

2005-02-01 Thread David Fraser
Sridhar wrote:
Hi,
I am doing my undergrade CS course.  I am in the final year, and would
like to do my project involving Python.  Our instructors require the
project to have novel ideas.  Can the c.l.p people shed light on this
topic?
You could write a Python program that writes novels.
--
http://mail.python.org/mailman/listinfo/python-list


Re: what's OOP's jargons and complexities?

2005-02-01 Thread Grumble
Pascal Bourguignon wrote:
You forgot to mention the coordinates of your secret mountain compound:
   28 deg 5 min N, 86 deg 58 min E
Mount Everest?
--
http://mail.python.org/mailman/listinfo/python-list


Programming challenge (C++ and Python)

2005-02-01 Thread Ali Polatel
    Dear Python friends,
    I need a favor.I play chess at a chess server with the name ICC(www.chessclub.com). I want to write a plugin for their interface using Python.
    I don't have any idea about how to write a plugin but I found out that the server administrator has written a Plugin Development Kit in C++ for those who wish to write plugins for the interface.I don't know C++ so I cannot convert this kit into python scripts.Can anyone do this for me? or can anyone examine those scripts and tell me a way how to write those with python?The development kit is avaliable at the site ftp://ftp.chessclub.com/pub/icc/interface/blitzin2/plugins/
under the name PluginDevkit.zip
Any kind of help is appreciated.
Regards,
Ali Polatel 
		Do you Yahoo!? 
Yahoo! Search presents - Jib Jab's 'Second Term'-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how do i create such a thing?

2005-02-01 Thread Lowell Kirsh
What might these exceptions be?
It's HIGHLY advisable to have your __getattr__ methods raise
AttributeError for any requested name that starts and ends with double
underscores, possibly with some specific and specifically designed
exceptions.
Alex
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using HTTPSConnection and verifying server's CRT

2005-02-01 Thread Marc Poulhiès
Marc Poulhiès <[EMAIL PROTECTED]> writes:

> [EMAIL PROTECTED] (Ng Pheng Siong) writes:

>> M2Crypto does server cert verification. With M2Crypto's httpslib, you pass
>> in an SSL.Context instance to the HTTPSConnection constructor to configure
>> the SSL; one of the config knobs is cert verification. So, redo your test,
>> satisfy yourself that this is doable, and send me your code to include as
>> an example in the distribution. ;-)

Hi again!

So here are few lines that do server's CRT check. I still have one
question: see in the code. Both have the exact same description on
the documentation.

Btw, thanks for your answer (this will save me from using Perl!)
 Marc

---8<---8<---8<---8<
#!/usr/bin/env python
import M2Crypto

ctx = M2Crypto.SSL.Context()

## what are the diff between these two??
#ctx.load_verify_info(cafile="/tmp/ca.crt")
ctx.load_verify_locations(cafile="/tmp/ca.crt")

# load client certificate (used to authenticate the client)
ctx.load_cert("/tmp/client.crt")

# stop if peer's certificate can't be verified
ctx.set_allow_unknown_ca(False)

# verify peer's certificate
ctx.set_verify(M2Crypto.SSL.verify_peer, 1)

con = M2Crypto.httpslib.HTTPSConnection("my.ssl.server.domain",ssl_context=ctx)

con.request("GET" , "/")
print con.getresponse().read()
---8<---8<---8<---8<-

Result here:
$ ./ssl_peer_verif.py 
Enter passphrase:
send: 'GET / HTTP/1.1\r\nHost: my.ssl.server.domain:443\r\nAccept-Encoding: 
identity\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Date: Tue, 01 Feb 2005 08:41:51 GMT
header: Server: Apache/2.0.46 (Red Hat)
header: Last-Modified: Mon, 31 Jan 2005 14:50:50 GMT
header: ETag: "4297-13-24658680"
header: Accept-Ranges: bytes
header: Content-Length: 19
header: Connection: close
header: Content-Type: text/html; charset=UTF-8
THIS IS WORKING =)
-- 
http://mail.python.org/mailman/listinfo/python-list


find isset() php function equivalent in python

2005-02-01 Thread Olivier Noblanc ATOUSOFT
Hello


What is the equivalent function of php isset() in python

Thank you very much.

olivier noblanc
http://www.logiciel-erp.fr 


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


Re: Forcing interactive interpreter without (-i)

2005-02-01 Thread Thomas Heller
Miki Tebeka <[EMAIL PROTECTED]> writes:

> Hello All,
>
> If there a way a script can tell Python to enter interactive mode even if
> the -i command line switch was not given?
>
> I want py2exe to create an interactive session, without writing my own
> REPL.

IIRC, in newer Python versions, you can set the PYTHONINSPECT env var inside
your script.

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


Re: tkinter: Can You Underline More Than 1 Char In A Menu Title

2005-02-01 Thread Tim Daneliuk
Fredrik Lundh wrote:
Tim Daneliuk wrote:

However, I intend to actually have two separate keys invoke this menu
to have it behave differently in different circumstances.
You can, of course, CHANGE the underlined character to match the
circumstances.
Yeah, I understand that ... what I want is two characters simulatenously
underlined ... oh well, another solution will be arranged...

if you want a menu choice to have different behaviour depending on what
key you use to invoke them, you should use two different choices.
 


That is my intention.  I have a menu that lists a set of regular expressions
available for a particular task.  However, the regex are applied in two
different ways for this task.  I want a common menu for displaying all
the choices, but two separate "Accelerator Keys" to invoke it, depending
on the desired application...
--

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
--
http://mail.python.org/mailman/listinfo/python-list


Re: find isset() php function equivalent in python

2005-02-01 Thread Ola Natvig
Olivier Noblanc ATOUSOFT wrote:
Hello
What is the equivalent function of php isset() in python
Thank you very much.
olivier noblanc
http://www.logiciel-erp.fr 


try:
if variable:
# isset
pass
except NameError:
# not set
pass

could work...
--
--
 Ola Natvig <[EMAIL PROTECTED]>
 infoSense AS / development
--
http://mail.python.org/mailman/listinfo/python-list


Re: find isset() php function equivalent in python

2005-02-01 Thread Max M
Ola Natvig wrote:
Olivier Noblanc ATOUSOFT wrote:
Hello
What is the equivalent function of php isset() in python
try:
if variable:
# isset
pass
except NameError:
# not set
pass

you could use:
>>> 'variable' in vars()
But be aware that it is bad bad practice to do it like that.
If you need variables that you don't know that name of, you should put 
them in a dictionary. They are made for that exact purpose.

>>> unkown_vars = {}
>>> unkown_vars['variable'] = 42
>>> 'variable' in unkown_vars
True
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: find isset() php function equivalent in python

2005-02-01 Thread Ola Natvig
Max M wrote:
Ola Natvig wrote:
Olivier Noblanc ATOUSOFT wrote:
Hello
What is the equivalent function of php isset() in python

try:
if variable:
# isset
pass
except NameError:
# not set
pass


you could use:
 >>> 'variable' in vars()
But be aware that it is bad bad practice to do it like that.
If you need variables that you don't know that name of, you should put 
them in a dictionary. They are made for that exact purpose.

 >>> unkown_vars = {}
 >>> unkown_vars['variable'] = 42
 >>> 'variable' in unkown_vars
True

If it's a greater possibility that the 'variable' are set than it's not 
you will get better performance when using:

try:
print unknown_vars['variable']
except KeyError:
print 'variable are not set'
istead of
if 'variable' in unknown_vars:
print unknown_vars['variable']
else:
print 'variable are not set'
You could even use
print unknown_vars.get('variable', 'variable are not set')
dictionary.get(key, default) returns the default if key are not located 
in the dictionary, I'm not sure if the function uses the try / except 
KeyError aproach or what it uses.

--
--
 Ola Natvig <[EMAIL PROTECTED]>
 infoSense AS / development
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python's idiom for function overloads

2005-02-01 Thread F. GEIGER
> > Since Python doesn't have static typing, how is the same result as
traditional
> > function overloads results in acheived?

The more you program in Python, the less you are missing it.

As Philippe already said, use objects that support the protocol or decide
what to do with it after having checked its type. I do that, if I have to,
like so:

def doIt(arg):
   if type(arg) == type([]):
  map(doIt, arg)
   else:
  # Do it on a scalar type
  # ...
  return result

HTH
Franz GEIGER


"Philippe Fremy" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> Hi Frans,
>
> > Since Python doesn't have static typing, how is the same result as
traditional
> > function overloads results in acheived?
>
> With dynamic typing obviously. :-)
>
> You can not reproduce the C++ overload idiom but you can get something
> close with manual type testing.
>
>  > To in a
>  > function do an if statement with the type() function?
>
> I am not aware of any other method.
>
> def a( arg1 ):
> if type(arg1) == types.IntType: return aWithInt(arg1)
> if type(arg1) == types.ListType: return aWithList(arg1)
> ...
>
> As you see, it is a bit tedious sometimes.
>
> If you want to juggle with completely different signatures, you have to
> play with variable argument lists. But I have found in my experience
> that the best way to get close to the C++ idiom, while improving
> readbility, is by using kwparams:
>
> def a(**kwparams):
> if kwparams.has_key('argInt'): aWithInt(kwparams['argInt'])
> if kwparams.has_key('argString'): aWithString(kwparams['argString'])
>
> The parsing code is the same, but the intent of the user is better
> expressed and you can catch misuse in a better fashion:
> if kwparams.has_key('argInt') and kwparams.has_key('argString'):
> print "You stupid moron, a can be used only with string or int but not
> both at the same time!"
> sys.exit(1)
>
> The example speaks better in a real case. Imagine a processPixmap
function:
> processPixmap( pixmap=QPixmap(...) )
> processPixmap( filename='my_pixmap.png' )
> processPixmap( buffer=my_pixmap_string_content )
>
> It works actually even better with multiple arguments.
>
> regards,
>
> Philippe


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


Re: variable declaration

2005-02-01 Thread Jacek Generowicz
"Michael Tobis" <[EMAIL PROTECTED]> writes:

> In fact, I'd recommend a paragraph early in the Nutshell book saying
> "there are no declarations, no use strict, no implicit none, sorry,
> forget it",

It would have to be a pretty long paragraph, if it were to list all
the things that you do NOT find in Python.

> and an index listing under "declarations" pointing to a detailed
> exegesis of their nonexistence.

Think about this. You are either asking that the book's author
anticipate your personal expectations, and write the book to cater for
YOUR PERSONAL expectiations ... or you are asking for a book with an
inifititely long index. The list of things absent from Python is
infinite.

> It would have saved me some time.

You don't want a book, you want a personal tutor.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's idiom for function overloads

2005-02-01 Thread Jacek Generowicz
Philippe Fremy <[EMAIL PROTECTED]> writes:

>   Hi Frans,
> 
> > Since Python doesn't have static typing, how is the same result as
> > traditional function overloads results in acheived?
> 
> 
> With dynamic typing obviously. :-)
> 
> You can not reproduce the C++ overload idiom

Of course you can. Use a multimethod of some sort.

The canonical answer to the OQ, of course, includes things like
"Consider whether you really want/need to do this" and "duck typing".

Frequently, in Python, code which checks for types, rather than
checking for features, ends up being excessively restrictive and
insufficiently general.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: variable declaration

2005-02-01 Thread Alex Martelli
Michael Tobis <[EMAIL PROTECTED]> wrote:

> Alex Martelli wrote:
> > Michael Tobis <[EMAIL PROTECTED]> wrote:
> 
> > he can perfectly
> > well correct his misexpression if he cares to -- not my job to try to
> > read his mind and perform exegesis on his words.
> 
> Well, I hate to try to tell you your job, but it doesn't seem to be to
> be all that great of a marketing strategy to actively chase people
> away... Hey, he might have been a Nutshell customer.

I'd far rather sell one fewer copy of the Nutshell, than sell one more
to somebody who is not _happy_ to use Python.


> > I think it would have been true, but weak and insufficient.  Not only
> > experienced Python users have that opinion: lack of declarations
> didn't
> > faze me even I was a total newbie
> 
> It did me, and it did many others. Perhaps you are unrepresentative.

Maybe; I did have good knowledge of a variety of languages, for example.
However, I have seen many people come upon ideas that were new to them
and meet them with interest and curiosity, even if initially doubtful
about the novelty, rather than with fear and loathing.  I think that
such an attitude is a better predictor of how happy a person will be
with Python (or other technologies he's initially unfamiliar with) than
"previously accumulated knowledge".


> It's one thing to say "no can do, sorry", it's another to say "you
> don't need this anyway and if you think you do you aren't worthy".

To say one is sorry about something that, in fact, makes one deliriously
happy, would be the worst sort of hypocrisy, even though it's a socially
common ``white lie''.  As for "worthy", that's a completely different
viewpoint, and I would appreciate it if you didn't put words into my
mouth.

Believing that somebody might be unhappy using Python (or any other
given technology), at least at this point in their personal development,
due to their ingrained mindset and strongly held opinions against one of
the cornerstones of the language, has nothing to do with "worth".


> In fact, it was your book I spent the most time thumbing through
> looking for the "use strict" equivalent that I was absolutely certain
> must exist. Hell, even Fortran eventually gave in to "IMPLICIT NONE".

...which has nothing to do with the case, since in Fortran, and from day
one, all names had statically determinable types anyway.

> It's practically the only thing I've ever expected to find in Python
> that hasn't vastly exceeded my expectations, aand I'm sure Alexander is
> not the only person to be put off by it.

By Hugol's Law, surely not.  So what?  If he sticks to his misguided
expectations, he won't be happy with Python.  If he outgrows them, he
probably will.  But the best way forwards is to get used to unit-testing
and thereby realize declarations are deadweight, THEN use a language
where they just aren't there.

> In fact, I'd recommend a
> paragraph early in the Nutshell book saying "there are no declarations,

What about a paragraph asking the reader to *READ* the book before
offering advice about it?  On p.32, "Python has no declarations"; on
p.39, under Variables, right at the start of the paragraph, "In Python,
there are no declarations.  The existence of a variable depends on a
statement that binds the variable, or, in other words, that sets
a name to hold a reference to some object".

Not only are these words pretty early, right towards the start of the
chapter giving an overview on the language, but I think the second
snippet has quite a prominent position.  If you're looking for a way to
declare variables, and don't think of looking at the very start of the
section titled "Variables" -- or if the words you find there,
reinforcing the previous assertion to the same effect, still keep you
"thumbing through" the book in search of what I just said isn't there, I
disclaim responsibility.

A book, particularly a quick reference, needs to be considered as a
_cooperative_ effort between writer and reader.  I can fairly be tasked
with expressing every important thing about the language, and I think I
do -- not all of the "sea lawyer"-level quibbles, but all of the aspects
most readers truly need.  But I cannot fairly be asked to *belabor*
every aspect that might faze some reader or other, to ward against the
reader not being careful and not realizing that, in a work where
conciseness is of the essence, every single word is there for a purpose.

If you need repetition and belaboring, get a book that's intended as
slow-paced tutorial.  Demanding tutorial-like repetitiousness of a
*quick reference* is absurd and irresponsible.

> no use strict, no implicit none, sorry, forget it", and an index

This is the second time you ask or suggest that I take an apologetic
attitude (or at least mouth platitudes that sound apologetic without
_meaning_ to be apologetic in the least), and I repeat: forget it.

> listing under "declarations" pointing to a detailed exegesis of their
> nonexistence. It would have saved me s

Re: how do i create such a thing?

2005-02-01 Thread Alex Martelli
Lowell Kirsh <[EMAIL PROTECTED]> wrote:

> What might these exceptions be?
> 
> > It's HIGHLY advisable to have your __getattr__ methods raise
> > AttributeError for any requested name that starts and ends with double
> > underscores, possibly with some specific and specifically designed
> > exceptions.

For example, delegation of such requests to some other object:
def __getattr__(self, name):
return getattr(self._delegate, name)

In such cases you may decide you do not need to block __specials__,
because you're OK with having self._delegate supply them or be
responsible to raise AttributeError if necessary.


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


Building Python with Tcl/Tk on Cygwin_NT-5.1

2005-02-01 Thread Dean N. Williams
Dear Python Community,
  I am trying to build Python with Tcl/Tk under the Cygwin_NT-5.1 OS. 
Has anyone done this? Do I need to build tcl8.4.9 and tk8.4.9 under the 
unix directory or the win directory. I found that the Tcl/Tk unix 
directories compiled just fine and built the libtcl8.4.a and libtk8.4.a 
libraries for use. But I don't think that Python is looking for this. If 
you've built Python with Tcl/Tck, is it possible for you to send me 
instructions on how you did it? Thanks in advance...

Best regards,
  Dean
--
http://mail.python.org/mailman/listinfo/python-list


Re: Forcing interactive interpreter without (-i)

2005-02-01 Thread Fuzzyman
In Movable Python I use IPython and code.InteractiveConsole to provide
interactive sessions.

See the file 'movpy.py' in the source distribution to see the code.
Note that to get IPython working with py2exe you must effectively do an
explicit `import site`.

>def interactive(localvars=None):
>"""A very simple function to embed an interactive interpreter into
movpy."""
# could have the banner passed in as an optional argument, plus
maybe the IPython config file location
>IPShellEmbed = None
>try:
>from IPython.Shell import IPShellEmbed
>except ImportError:
>pass

>if not IPShellEmbed or IPOFF:
>if localvars == None:
>localvars = sys._getframe(0).f_back.f_locals#
extract locals from the calling frame - taken from IPython
>from code import InteractiveConsole
>con = InteractiveConsole(localvars)
>con.interact()
>else:
>banner = 'Movable Python\nIPython Interactive Shell. See the
manual for a list of features and tips.\nCtrl-D to exit.'
>argv = ['-ipythondir', libdir]  # where to find
the ipython config file
>ipshell = IPShellEmbed(argv, banner=banner)
>ipshell()

http://sourceforge.net/projects/movpy
Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


Re: Python's idiom for function overloads

2005-02-01 Thread Jacek Generowicz
"F. GEIGER" <[EMAIL PROTECTED]> writes:

> As Philippe already said, use objects that support the protocol or decide
> what to do with it after having checked its type. I do that, if I have to,
> like so:
> 
> 1  def doIt(arg):
> 2if type(arg) == type([]):
> 3map(doIt, arg)
> 4 else:
> 5# Do it on a scalar type
> 6# ...
> 7return result

Now, consider that line 3 would execute very happily if the type of
arg were 

1) list, 
2) str,
3) tuple,
4) dict,
5) file,
6) any other built-in iterable or sequence,
7) any useer-defined iterable or sequence,
8) a subclass of any of the above,
9) god knows what else ...

... yet in line 2 you have ensured that the whole function will not
work properly for any of the listed types other than the first.

You could make the code much more general by doing it like this:

try:
map(doIt, arg)
except TypeError:
...


The important thing to note is that the actual types of Python objects
are usually not very interesting or important at all. What is much
more important is what the object is able to do: what messages it
understands, what protocols it supports.

Hiding some code behind a type-check, in Python, is quite frequently
the wrong thing to do.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Next step after pychecker

2005-02-01 Thread huy
Paul Rubin wrote:
Philippe Fremy <[EMAIL PROTECTED]> writes:
I would like to develop a tool that goes one step further than
pychecker to ensure python program validity. The idea would be to get
close to what people get on ocaml: a static verification of all types
of the program, without any kind of variable declaration. This would
definitely brings a lot of power to python.

You know, I've always thought that ML-style type inference is an
impressive technical feat, but why is it so important to not use
declarations?  This is an aspect I've never really understood.
You know, I think I agree ;-). Just because you don't declare the types, 
doesn't mean you can change the implicit type willy nilly anyway; at 
least for more complex programs anyway. In fact, it would be safer to 
have type checking when you want to do something like this. I currently 
needed to change a number parameter to a string parameter (found out 
order_no wasn't just numbers as specs had specified). Of course this 
parameter was being used in a great many places. Changing it was a bit 
scary because we had to make sure it wasn't being treated as a number 
anywhere throughout the code. Yes good coverage with unit tests would 
have helped but unfortunately we do not yet have good coverage. TDD is a 
quite hard to practice as a beginner.

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


type of simple object

2005-02-01 Thread [EMAIL PROTECTED]
Hi,

How do I know type of simple object is tuple or list or integer, for
example my function should understand what is the object type passed in
its argument

Pujo

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


Re: Python's idiom for function overloads

2005-02-01 Thread Philippe Fremy

Frequently, in Python, code which checks for types, rather than
checking for features, ends up being excessively restrictive and
insufficiently general.
That's true, but checking for the exact features that are going to be 
needed by your code is usually quite complicated and painful to 
maintain. At the beginning, you need only a sequence. In the end, you 
need a mutable sequence that supports slicing, so you could go by 
requiring a list as well.

Enforcing types also brings the benefit that the program is more 
deterministic. In my experience, there is a lot more benefits to have an 
object whose type is clearly identified than to have function that 
accepts generic objects.

I would go as far as saying that variables should have immutable types. 
It is more restricting that what python provides currently, but leads to 
clearer programming practice: the intent of the developer shows up in 
the type he uses.

Of course, with languages such as OCaml, you get both of it: liberal 
typing with enforced consistency.

While Python's dynamic typing liberty is enjoyable, I think it harms 
when you start to work on big projects. It prevents you to put many 
safety assumptions which might bite you back.

regards,
Philippe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Next step after pychecker

2005-02-01 Thread Jacek Generowicz
Paul Rubin  writes:

> Philippe Fremy <[EMAIL PROTECTED]> writes:
> > I would like to develop a tool that goes one step further than
> > pychecker to ensure python program validity. The idea would be to get
> > close to what people get on ocaml: a static verification of all types
> > of the program, without any kind of variable declaration. This would
> > definitely brings a lot of power to python.
> 
> You know, I've always thought that ML-style type inference is an
> impressive technical feat, but why is it so important to not use
> declarations?  This is an aspect I've never really understood.

You gain something akin to duck typing, though in a formalized way
(type classes). The code works for any types which provide the
features which are used in the code, without regard for the specific
type. You gain generic programming.

You also gain not having to clutter your code with all the type
declarations. And you gain not having to decide what types you will
use too early on in development.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: type of simple object

2005-02-01 Thread ech0
use the type function!

>>> s = 'test'
>>> i = 25
>>> type(s)

>>> type(i)


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


Re: variable declaration

2005-02-01 Thread Arthur
On 31 Jan 2005 19:41:27 -0800, "Michael Tobis" <[EMAIL PROTECTED]> wrote:

>> You may call it a strawberry, if you wish, but that doesn't mean it
>will
>> taste good with fresh cream.  It's nothing more and nothing less than
>an
>> arguably weird syntax for a perfectly executable statement:
>
>This may well be true in implementation, but cognitively it is a
>declaration that modifies the reference and not the referent. I see
>that it is a big deal to ask for more of these, but I don't see why.

Thank you for bringing it and respecting the cognitive factor.  My
"expereince* of the decorator, disassembly of internals quite aside,
is that it breaks old rules - or, if prferred, breaks new ground -  by
impacting code one wouildn't expect it to kow about.

It frightens me a bit when the road to Guru seems to move in the
direction of most completely transcending the normal user experience,
rather than in best comprehending it.

Art

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


Re: type of simple object

2005-02-01 Thread Jacek Generowicz
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> How do I know type of simple object is tuple or list or integer, for
> example my function should understand what is the object type passed in
> its argument


Answers ordered in decreasing degree of Pythonicity:

1) You are mistaken, the function almost certainly should not care
   whether the object is a tuple or a list (or integer)[1].

2) isinstance(obj, list) etc.

3) type(obj)



[1] You probably want to check whether the object is capable of doing
whatever it is that you expect lists or tuples to do for you. For
example: 


def total(object):
try:
return sum(object) # The list-or-tuple case
except TypeError:
return object  # The integer case

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


Re: Python's idiom for function overloads

2005-02-01 Thread Jacek Generowicz
Philippe Fremy <[EMAIL PROTECTED]> writes:

> Enforcing types also brings the benefit that the program is more
> deterministic. In my experience, there is a lot more benefits to have
> an object whose type is clearly identified than to have function that
> accepts generic objects.
> 
> 
> I would go as far as saying that variables should have immutable
> types.

If you really believe this, then I would go as far as saying that you
would be happier in a language other than Python.

> It is more restricting that what python provides currently, but
> leads to clearer programming practice: the intent of the developer
> shows up in the type he uses.

Not in my opinion or experience.

To each his own, and vice versa.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: type of simple object

2005-02-01 Thread [EMAIL PROTECTED]
The result 
How can I check it since it is not a string right?

Pujo

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


python ScriptControl error in Excel while running fine in python

2005-02-01 Thread Sebastien de Menten
I am trying to use ScriptControl under Excel (Windows XP) with the
code:

Global sc As New MSScriptControl.ScriptControl

Public Function os_getcwd()
sc.Language = "python"
sc.ExecuteStatement ("import os")
os_getcwd = sc.Eval("os.getcwd()")
End Function

When setting the language to python I have the error "A script engine
for the specified language..."

On the other side, under python, the translated code:

import win32com.client

sc=win32com.client.Dispatch("ScriptControl")
sc.Language = "python"
sc.ExecuteStatement ("import os")
print sc.Eval("os.getcwd()")

works without any problem !

So, is it possible that a different set of permissions for languages
available in ScriptControl is used when executed from Excel or from
python ?
Is it possible to ask the available languages to ScriptControl ?

Well, in fact I am totally puzzled by this behaviour so any help is
welcome :-)

Sebastien

PS: could you reply to my email address as I do not read regularly
c.l.p. ? thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Python's idiom for function overloads

2005-02-01 Thread Tim Golden
[Jacek Generowicz]
| 
| To each his own, and vice versa.

Vice versa? :)

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Remove HTML tags (except anchor tag) from a string using regular expressions

2005-02-01 Thread Nico Grubert
Hello,
I want to remove all html tags from a string "content" except xxx.

My script reads like this:
###
import re
content = re.sub('<([^!>]([^>]|\n)*)>', '', content)
###
It works fine. It removes all html tags from "content".
Unfortunately, this also removes  xxx occurancies.
Any idea, how to modify this to remove all html tags except xxx?
Thanks in advance,
Nico
--
http://mail.python.org/mailman/listinfo/python-list


Re: "pickle" vs. f.write()

2005-02-01 Thread mmiller at tx3 dot com
On 1/26/05 at 1:48 pm, Terry Reedy wrote:
> For basic builtin objects, repr(ob) generally produces a string that when 
> eval()ed will recreate the object.  IE
> eval(repr(ob) == ob # sometimes

I've found extending this property to your own classes often fairly easy
to implement (and useful). For example:

> class person:
> def __init__(self, name="", age=0, friends=None, comment=""):
> if friends is None:
> friends = []
> self.name, self.age, self.friends, self.comment = name, age, friends, 
> comment
> 
> def __repr__(self):
> return ("person(" + repr(self.name) + ", " + repr(self.age) + ", " +
> repr(self.friends) +  ", " + repr(self.comment) + ")")
> 
> me = person()
> 
> print "me =", repr(me)

Which produces the following output:
   me = person('', 0, [], '')


In addition, the following constructs are possible:

> family = [
> person("Martin", 50, ["Matt"], "eldest son"),
> person("Matt", 43, ["Martin"], "youngest son"),
> person("Merry", 72, ["Martin", "Matt"], "mother"),
> person("Luther", 82, ["Merry"], "father")
> ]
> 
> print "family =", repr(family)

Which output the following:
family = [person('Martin', 50, [], 'eldest son'), person('Matt', 43,
['Martin'], 'youngest son'), person('Merry', 72, ['Martin', 'Matt'],
'mother'), person('Luther', 82, ['Merry'], 'father')]

Basically this approach allows you to store your data in Python source
files -- which you can then import or execfile. The files can also
contain comments and are relatively easy to edit by hand. In addition
they're portable.

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


Re: "pickle" vs. f.write()

2005-02-01 Thread Martin Miller
On 1/26/05 at 1:48 pm, Terry Reedy wrote:
> For basic builtin objects, repr(ob) generally produces a string that when 
> eval()ed will recreate the object.  IE
> eval(repr(ob) == ob # sometimes

I've found extending this property to your own classes often fairly easy
to implement (and useful). For example:

> class person:
> def __init__(self, name="", age=0, friends=None, comment=""):
> if friends is None:
> friends = []
> self.name, self.age, self.friends, self.comment = name, age, friends, 
> comment
> 
> def __repr__(self):
> return ("person(" + repr(self.name) + ", " + repr(self.age) + ", " +
> repr(self.friends) +  ", " + repr(self.comment) + ")")
> 
> me = person()
> 
> print "me =", repr(me)

Which produces the following output:
   me = person('', 0, [], '')


In addition, the following constructs are possible:

> family = [
> person("Martin", 50, ["Matt"], "eldest son"),
> person("Matt", 43, ["Martin"], "youngest son"),
> person("Merry", 72, ["Martin", "Matt"], "mother"),
> person("Luther", 82, ["Merry"], "father")
> ]
> 
> print "family =", repr(family)

Which output the following:
family = [person('Martin', 50, [], 'eldest son'), person('Matt', 43,
['Martin'], 'youngest son'), person('Merry', 72, ['Martin', 'Matt'],
'mother'), person('Luther', 82, ['Merry'], 'father')]

Basically this approach allows you to store your data in Python source
files -- which you can then import or execfile. The files can also
contain comments and are relatively easy to edit by hand. In addition
they're portable.

Best,
Martin


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


Re: Python's idiom for function overloads

2005-02-01 Thread F. Petitjean
Le Tue, 01 Feb 2005 12:10:47 +0100, Philippe Fremy a écrit :
> 
>> Frequently, in Python, code which checks for types, rather than
>> checking for features, ends up being excessively restrictive and
>> insufficiently general.
> 
snip
> 
> Enforcing types also brings the benefit that the program is more 
> deterministic. In my experience, there is a lot more benefits to have an 
> object whose type is clearly identified than to have function that 
> accepts generic objects.
If you insist to always have only clearly identified types of variables
you will use the Hungarian notation :
bool bIsDir = blah
const char *lpszMessage = "It's a directory";
> 
> I would go as far as saying that variables should have immutable types. 
> It is more restricting that what python provides currently, but leads to 
> clearer programming practice: the intent of the developer shows up in 
> the type he uses.
clearer programming practice which goes with unreadable code ?
> 
> 
> While Python's dynamic typing liberty is enjoyable, I think it harms 
> when you start to work on big projects. It prevents you to put many 
> safety assumptions which might bite you back.
Python is strongly typed (at run-time). You can get a traceback sure but
it is rather difficult to get unreliable results.
> 
>   regards,
> 
>   Philippe
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggesion for an undergrad final year project in Python

2005-02-01 Thread Kartic
Sridhar said the following on 2/1/2005 2:11 AM:
Hi,
I am doing my undergrade CS course.  I am in the final year, and would
like to do my project involving Python.  Our instructors require the
project to have novel ideas.  Can the c.l.p people shed light on this
topic?
You try and implement some CS concepts you have learnt using Python. For 
example, if you had a course on parsing and compiler design, try to 
implement a simple language in Python.

Or if you like Computer Graphics, see if you can implement things like 
Phong shading and things in that field. This may not be novel like your 
professors want. But you can make it novel by allowing the user to 
rotate the object and show how the shadow and shading get transformed.

Or if you are the networking types, come up with a peer-to-peer chat 
application with whitetboard capability, which I am sure will be fairly 
novel.

Look within for answers :-)
That way you will reinforce your theory and learn Python as well.
Thanks,
--Kartic
--
http://mail.python.org/mailman/listinfo/python-list


Re: type of simple object

2005-02-01 Thread Jacek Generowicz
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> The result 
> How can I check it since it is not a string right?

It is a type, which is a first-class object in its own right.

type('hello') == str

However, I reiterate, you almost certainly don't really care about
what the actual type is. To care about the actual type is to struggle
against a fundamental feature of python: Duck Typing.

Yes, I admit, there are situations in which you might really care
about the actual type. However, given that you do not know how to
check the type in Python, the chances are rather high that you are
sufficienly new to Python to not realize that, typically, you need not
(and should not) care about the actual type. The chances are that you
are trying to program in a style which you learned in another
language, and which not the most productive in Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: type of simple object

2005-02-01 Thread [EMAIL PROTECTED]
Thank you guys.

My function should multiply every element  of a list, for example
"something"
and "something" can be an integer or another list.
If it deals with integer than it is ok, but
If it deals with list than it become false for example list*2 =
listlist, and what I really want is to mutlitply its member.
That's why I need to know the type of my data in "something".

By the way I am new in python, I heard that it has a MatLab
capabilities, How good is that? Since It would be very nice when we can
do what MatLab do in python.


Sincerely Yours,
pujo

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


Re: Remove HTML tags (except anchor tag) from a string using regular expressions

2005-02-01 Thread Anand
How about...

import re
content = re.sub('<([^!(a>)]([^(/a>)]|\n)*)>', '', content)
Seems to work for me.

HTH

-Anand

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


Re: Building Python with Tcl/Tk on Cygwin_NT-5.1

2005-02-01 Thread Jason Tishler
Dean,

On Tue, Feb 01, 2005 at 02:31:03AM -0800, Dean N. Williams wrote:
> I am trying to build Python with Tcl/Tk under the Cygwin_NT-5.1 OS. 
> Has anyone done this?

Yes, Cygwin Python with _tkinter has been part of the standard Cygwin
distribution for over three years:

http://www.cygwin.com/ml/cygwin-announce/2001/msg00118.html

> Do I need to build tcl8.4.9 and tk8.4.9 under the unix directory or
> the win directory.

No, Tcl/Tk is part of the standard Cygwin distribution too.

> I found that the Tcl/Tk unix directories compiled just fine and built
> the libtcl8.4.a and libtk8.4.a libraries for use. But I don't think
> that Python is looking for this. If you've built Python with Tcl/Tck,
> is it possible for you to send me instructions on how you did it?

See the Cygwin Python README:

http://www.tishler.net/jason/software/python/python-2.4.README

BTW, why don't you just use the pre-built Cygwin Python?

Jason

-- 
PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers
Fingerprint: 7A73 1405 7F2B E669 C19D  8784 1AFD E4CC ECF4 8EF6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Go visit Xah Lee's home page

2005-02-01 Thread Arthur
On Mon, 31 Jan 2005 16:07:41 -0800, aurora <[EMAIL PROTECTED]> wrote:

>Let's stop discussing about the perl-python non-sense. It is so boring.
>
>For a break, just visit Mr Xah Lee's personal page  
>(http://xahlee.org/PageTwo_dir/Personal_dir/xah.html). You'll find lot of  
>funny information and quotes from this queer personality. Thankfully no  
>perl-python stuff there.
>
>Don't miss Mr. Xah Lee's recent pictures at
>
>   http://xahlee.org/PageTwo_dir/Personal_dir/mi_pixra.html
>
>My favor is the last picture. Long haired Xah Lee sitting contemplatively  
>in the living room. The caption says "my beautiful hair, fails to resolve  
>the problems of humanity. And, it is falling apart by age."


And of each of us contributed something 50% as worthwhile as well
executed as his geometry pages to the Web, the Web would begin to
deliver 10% of its promise.

POST GET this ;)

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


Re: type of simple object

2005-02-01 Thread Jacek Generowicz
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> Thank you guys.
> 
> My function should multiply every element  of a list, for example
> "something"
> and "something" can be an integer or another list.
> If it deals with integer than it is ok, but
> If it deals with list than it become false for example list*2 =
> listlist, and what I really want is to mutlitply its member.

Which member? A list can have many members ... or none at all.

> That's why I need to know the type of my data in "something".

No, you don't need to know its type at all. You need to know whether
it is a sequence or not ... which is a far cry from knowing its type.

> By the way I am new in python, I heard that it has a MatLab
> capabilities, How good is that?

Depends on what you mean by "MatLab capabilities". Matlab is highly
matrix oriented, therefore it provides lots of fast matrix operations,
and syntactic sugar for dealing with matrices. If you want to think of
everything as a matrix, then you could well be disappointed by
Python. 

There is a package for driving matlab from Python, which you might
find interesting (it might even be what you meant by "MatLab
capabilities"). Google is your friend.
-- 
http://mail.python.org/mailman/listinfo/python-list


equivelant of Java's toString() method? (not repr)

2005-02-01 Thread Alex Hunsley
Pretty simple seeming question, but can't find answer via google or docs...
I am using urllib2 as follows:
 handle = urlopen(req, postdata) # and URL to return a handle 
on
 ...
 print handle.info()

the print statement prints out the headers:
Content-Type: text/html;charset=ISO-8859-1
Content-Length: 2845
Date: Tue, 01 Feb 2005 12:40:28 GMT
Server: Apache Coyote/1.0
Connection: close
which is the string I want to use.
However, if I write a function call using this:
  log(handle.info())
I get this:
 TypeError: cannot concatenate 'str' and 'instance' objects
(The log function expects a string)
What is the magic incantation to get the string I want so I can pass it 
to my function?
I've tried repr() but that isn't it (I suspected it wouldn't be).
I suppose I'm looking for the equivelant of Java's toString() method...

thanks!
alex

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


Re: equivelant of Java's toString() method? (not repr)

2005-02-01 Thread Alex Hunsley
Alex Hunsley wrote:
Pretty simple seeming question, but can't find answer via google or docs...
I am using urllib2 as follows:
 handle = urlopen(req, postdata) # and URL to return a handle on
 ...
 print handle.info()
the print statement prints out the headers:
Content-Type: text/html;charset=ISO-8859-1
Content-Length: 2845
Date: Tue, 01 Feb 2005 12:40:28 GMT
Server: Apache Coyote/1.0
Connection: close
which is the string I want to use.
However, if I write a function call using this:
  log(handle.info())
I get this:
 TypeError: cannot concatenate 'str' and 'instance' objects
(The log function expects a string)
What is the magic incantation to get the string I want so I can pass it 
to my function?
I've tried repr() but that isn't it (I suspected it wouldn't be).
I suppose I'm looking for the equivelant of Java's toString() method...

thanks!
alex
Replying to meself...
D'oh! Just found the str() function which is just what I need!
log(str(handle.info())) works fine
thx
alex
--
http://mail.python.org/mailman/listinfo/python-list


Re: equivelant of Java's toString() method? (not repr)

2005-02-01 Thread Roy Smith
Alex Hunsley <[EMAIL PROTECTED]> wrote:
> I suppose I'm looking for the equivelant of Java's toString() method...

That would be str(), which for the most part, just calls your object's 
__str__() method.  If your object doesn't have an __str__() method, there's 
nothing magic Python can do to invent one.

The difference between repr() and str() is that repr() is supposed to 
produce a parsable representation of the object; one which could be parsed 
by a Python interpreter to re-generate the original object.  On the other 
hand, str() is supposed to produce a human-readable string.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Remove HTML tags (except anchor tag) from a string using regular expressions

2005-02-01 Thread Anand
I meant
content = re.sub ('<[^!(a>)]([^>]|\n)*[^!(/a)]>', '', content)

Sorry for the mistake.
However this seems to also print tags like ,  etc
also.

-Anand

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


Re: Advice on OSX cocoa app with Python backend

2005-02-01 Thread Steve Holden
Socheat Sou wrote:
After a brief, but informative, discussion on Freenode's  #zope
chatroom, I was advised to consult the gurus on c.l.p.
I'm working for a small company who is in desperate need to rewrite it's
15+ year old, flat-file, client-tracking database.  The staff uses OSX,
while I administer the couple linux servers we have to run our website
and some internal sites.  In our initial brainstorming session, we
decided to go with a Python backend server, handling the database and
business logic, and a native Cocoa application on the client side, with
enough glue to make the two stick.
Sounds like a plan, for a Mac house.
Also, after a bit of research, I discovered Twisted and PB.  I figured
I'd have to write a customized backend to meet our needs.  However,
seeing as how 1) I've never written a netwo
rk application before, let alone a multi-threaded application and 2) I'm
the sole developer
 on this project, I was looking for as many API's, modules, frameworks,
and/or prebuilt solutions as possible to help me out.
First of all, note that Twisted applications needn't be multi-threaded, 
as Twisted makes use of asynchronous interfaces. You *can* write 
multi-threaded code under Twisted, but you don't have to most of the time.

I initially thought of Zope because I had often heard it referred to as
an application serv
er, so I thought it might be something I could use as a basis, write the
business logic, and have the Cocoa application, with some PyObjC,
communicate with the Zope server.  We're definately not looking for a
web-based application, so I wasn't quite sure Zope was what I wa
nted.
It isn't. Much too heavyweight, with much too steep a learning curve for 
what appears to be essentially a simple project.

For those that are interested, we're looking at using MySQL as the DBMS.
From what little I know of OODBMS it doesn't seem like the right choice
because aside from data entry and client record lookups, the biggest use
of the database would be to generate reports and tabulated data on an
arbitrary set of fields.  I've read that this isn't exactly the strength
of OODBMS?
Who told you that MySQL was OO? It's a bog-standard relational back-end 
with transactional capabilities.

We are also looking at a server-client architecture, rather than
individual clients connecting to the database over the network, because
there are some features the staff would like (such as something similar
to message passing between each other, and also being able to administer
connected users).
So you need a(t least one) layer between the database and the client, 
which you plan to write in Python. This makes perfect sense. Almost 
everything you find about writing servers in Python is going to work for 
you, so Google away!

Does anyone here have any experience building an OSX application with
Python running the show behind the scenes?  I hope I didn't come off as
asking "tell me what to do", but rather I would appreciate any advice or
links to resources that might be helpful in this project.
Mostly, remember that OSX is effectively just another U**x environment, 
so server structures that work under BSD and Linux will tend to work 
under OSX. The unique parts of OSX appear (from the outside) to be 
Carbon/Cocoa and the funky GUI stuff. So have at it and come back for 
advice when you need it. Good luck with your project.

[OBPyCon: of course, if you come to PyCon DC 2005 you can discuss this 
stuff with experts:

  http://www.python.org/pycon/2005/register.html
The numbers tell us this could be the biggest PyCon ever!]
regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: equivelant of Java's toString() method? (not repr)

2005-02-01 Thread Ola Natvig
Alex Hunsley wrote:
Pretty simple seeming question, but can't find answer via google or docs...
I am using urllib2 as follows:
 handle = urlopen(req, postdata) # and URL to return a handle on
 ...
 print handle.info()
the print statement prints out the headers:
Content-Type: text/html;charset=ISO-8859-1
Content-Length: 2845
Date: Tue, 01 Feb 2005 12:40:28 GMT
Server: Apache Coyote/1.0
Connection: close
which is the string I want to use.
However, if I write a function call using this:
  log(handle.info())
I get this:
 TypeError: cannot concatenate 'str' and 'instance' objects
(The log function expects a string)
What is the magic incantation to get the string I want so I can pass it 
to my function?
I've tried repr() but that isn't it (I suspected it wouldn't be).
I suppose I'm looking for the equivelant of Java's toString() method...

thanks!
alex


use:
log(str(handle.info()))
str creates a string object from a supplied object with a __str__ 
method. I think print calls str on what it is going to print


--
--
 Ola Natvig <[EMAIL PROTECTED]>
 infoSense AS / development
--
http://mail.python.org/mailman/listinfo/python-list


PyCon signature advertising

2005-02-01 Thread Steve Holden
You will note that I have changed my signature for newsgroups to include 
a plug for PyCon. I would very much appreciate any similar changes that 
c.l.py readers felt able to make to help get the word out that PyCon is 
*the* place to be for Python users and developers.

I appreciate that not everyone has control over their .sig, and that 
some people find advertising of this crassly commercial nature a little 
distasteful. If either of these is the case, please simply ignore this 
message (though you should, of course, still come to PyCon :-)

Every little helps, however, and  I'd like my third (and final) year as 
chairman to see the biggest and (much more importantly) best PyCon ever. 
I hope to meet as many of you as possible in DC, March 23-25 (and during 
the four-day sprint preceding the main event).

regards
 Steve
--
Meet the Python developers and your c.l.py favorites
Come to PyCon  http://www.python.org/pycon/2005/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: type of simple object

2005-02-01 Thread [EMAIL PROTECTED]
Hello Jacek,

Thanks for the answer,

Can you tell me how can I check if an object is a sequence (you are
right, this is actually what I want)?

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


Re: Suggesion for an undergrad final year project in Python

2005-02-01 Thread Paul Robson
On Tue, 01 Feb 2005 12:11:47 +, Kartic wrote:

> Sridhar said the following on 2/1/2005 2:11 AM:
>> Hi,
>> 
>> I am doing my undergrade CS course.  I am in the final year, and would
>> like to do my project involving Python.  Our instructors require the
>> project to have novel ideas.  Can the c.l.p people shed light on this
>> topic?
> 
> You try and implement some CS concepts you have learnt using Python. For 
> example, if you had a course on parsing and compiler design, try to 
> implement a simple language in Python.

Could I suggest going for an area that particularly interests you ; rather
than saying "what sort of project " come up with an area of interest -
this'll mean you probably have more knowledge and will put in more
effort - and then ask for ideas - ideally about something that is missing.

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


[OT] post-structuralist object oriented system

2005-02-01 Thread PA
For your entertainment:
"Lua’s Story of O"
http://alt.textdrive.com/lua/19/lua-story-of-o
Cheers
--
PA, Onnay Equitursay
http://alt.textdrive.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Next step after pychecker

2005-02-01 Thread Sylvain Thenault
On Tue, 01 Feb 2005 05:18:12 +0100, Philippe Fremy wrote:
>   Hi,

Hi

> I would like to develop a tool that goes one step further than pychecker
> to ensure python program validity. The idea would be to get close to what
> people get on ocaml: a static verification of all types of the program,
> without any kind of variable declaration. This would definitely brings a
> lot of power to python.
> 
> The idea is to analyse the whole program, identify constraints on function
> arguments and check that these constraints are verified by other parts of
> the program.

Did you take a look at the starkiller [1] and pypy projects [2] ?

> What is in your opinion the best tool to achieve this ? I had an
> extensive look at pychecker, and it could certainly be extended to do
> the job. Things that still concern me are that it works on the bytecode,
> which prevents it from working with jython and the new .NET python.
> 
> I am currently reading the documentation on AST and visitor, but I am
> not sure that this will be the best tool either. The AST seems quite
> deep and I am afraid that it will make the analysis quite slow and
> complicated.
 
are you talking about the ast returned by the "parser" module, or the ast
from the "compiler" module ? The former is a higher abstraction, using
specific class instances in the tree, and most importantly with all the
parsing junk removed. See [3]. You may also be interested in pylint
[4] which is a pychecker like program built in top of the compiler ast,
and so doesn't require actual import of the analyzed code. However it's
not yet as advanced as pychecker regarding bug detection.

And finally as another poster said you should probably keep an eye open
on the python 2.5 ast branch work...

Hope that helps !

[1]http://www.python.org/pycon/dc2004/papers/1/paper.pdf)
[2]http://codespeak.net/pypy/index.cgi?home
[3]http://www.python.org/doc/current/lib/module-compiler.ast.html
[4]http://www.logilab.org/projects/pylint

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

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


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


Re: Remove HTML tags (except anchor tag) from a string using regular expressions

2005-02-01 Thread Max M
Nico Grubert wrote:
If it's not to learn, and you simply want it to work, try out this library:
http://zope.org/Members/chrisw/StripOGram/readme
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyCon signature advertising

2005-02-01 Thread Mike C. Fletcher
Steve Holden wrote:
...
I appreciate that not everyone has control over their .sig,
...
Take control of your sigs, my sisters and brothers!  Viva la 
Revolution!  Follow the Steve into the heat and light of PyCon.  You can 
achieve enlightenment if only you go to the District on the Eastern Edge 
of the new continents when the spring arrives.  It is only there that 
all will be revealed.  It is only there that you shall find peace.

Joy to the Python world!
Mike

 Mike C. Fletcher
 Designer, VR Plumber, Coder
 http://www.vrplumber.com
 http://blog.vrplumber.com
 PyCon is coming...
--
http://mail.python.org/mailman/listinfo/python-list


Re: type of simple object

2005-02-01 Thread Diez B. Roggisch
> Can you tell me how can I check if an object is a sequence (you are
> right, this is actually what I want)?

read the docs for the module "types."
-- 
Regards,

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


Re: PyCon signature advertising

2005-02-01 Thread Steve Holden
Mike C. Fletcher wrote:
Steve Holden wrote:

I appreciate that not everyone has control over their .sig,


Take control of your sigs, my sisters and brothers!  Viva la 
Revolution!  Follow the Steve into the heat and light of PyCon.  You can 
achieve enlightenment if only you go to the District on the Eastern Edge 
of the new continents when the spring arrives.  It is only there that 
all will be revealed.  It is only there that you shall find peace.

Joy to the Python world!
Mike

 Mike C. Fletcher
 Designer, VR Plumber, Coder
 http://www.vrplumber.com
 http://blog.vrplumber.com
 PyCon is coming...
That's the spirit! Of course, a URL wouldn't hurt ;-)
backing-away-smiling-ly y'rs  - steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.python.org/pycon/2005/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyCon signature advertising

2005-02-01 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 "Mike C. Fletcher" <[EMAIL PROTECTED]> wrote:

> Steve Holden wrote:
> ...
> 
> > I appreciate that not everyone has control over their .sig,
> 
> ...
> 
> Take control of your sigs, my sisters and brothers!  Viva la 
> Revolution!  Follow the Steve into the heat and light of PyCon.  You can 
> achieve enlightenment if only you go to the District on the Eastern Edge 
> of the new continents when the spring arrives.  It is only there that 
> all will be revealed.  It is only there that you shall find peace.
> 
> Joy to the Python world!
> Mike

And the smallest child asked:

Why is this language different from all other languages?.

In all other languages, we are driven to declare our variables in a static 
manner, as surely as the compiler compels us to know their types ahead of 
time, and be forced to invoke the power of the reinterpret_cast whenever we 
need to deviate from the straight path laid out for us.  Why do we not in 
this language?

In all other languages, we may indent as we please, depending on the twin 
angels of the curly-brace and the semicolon to discern the true meaning 
from the meanderings of our code across the pages of our printouts.  Why do 
we indent with tabs as rigidly as the rows of corn in our fields in this 
language?

In all other languages, we omit explicit references to self, trusting to 
context to determine the scope of our variables.  Why in this language do 
we speak our own name with overbearing monotony each time we refer to an 
instance variable?

In all other languages, we are forced to choose between object orientation 
and procedural code and bear the burden of our choice all through the long 
days of the project lifecycle.  Why in this language are we free to mix 
paradigms, even to the point of using functional programming constructs 
only whenever they seem cool and useful without fear of retribution from 
the methodology police?

Then the smallest child was silent, and the old man began to speak.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Next step after pychecker

2005-02-01 Thread Peter Maas
Jacek Generowicz schrieb:
You also gain not having to clutter your code with all the type
declarations. And you gain not having to decide what types you will
use too early on in development.
But it can be useful to restrict type variety in certain situations
e.g. prime number calculation :) And it would probably also be useful
to check violations of restrictions before running the program in
normal mode.
This must not necessarily mean 'int this, float that'. E.g. the
following would be nice:
a := some_type_value  # "type fixing" assignment
a = other_type_value  # error: a is restricted to some_type
a := yet_another_type_value  # OK, another fixed type is set
del a # release type restriction; a can be recreated in normal
  # dynamic mode
The type fixing assignment could be used for optimization and for
checking the program with pychecker.
--
---
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
---
--
http://mail.python.org/mailman/listinfo/python-list


Re: variable declaration

2005-02-01 Thread Thomas Bartkus

"Carl Banks" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]


> How common is it for a local variable to be bound in
> more than one place within a function?

How common?  It shouldn't happen at all and that was the point.
The original posters code demonstrates how it can occur inadvertently as a
result of a simple typographical error.

You won't hear me claim that Python is without mitigating virtues. Clearly,
there is much about Python that encourages good design which will in turn
reduce the incidence of such errors. Nevertheless, one has to admit to this
blemish.  One also wonders if it is really necessary to endure what looks to
me like an omission.  Is there a reason why the interpreter
couldn't/shouldn't require formal declarations?

I, too, wish there were a switch like VBs "Option Explicit" that would
require you to declare "epsilon = 0" and thereafter have the interpretor
refuse assignment to an undeclared "epselon". Sane VB programmers (and yes,
there are a few!) leave it on by default and consider it abomination that
the switch is optional. The original posters example was a good one.  I had
to take a good long stare before I saw it even though the code is short,
sweet, and otherwise correct.

*Is* there a reason why the interpreter couldn't/shouldn't require formal
variable declaration?
It seems to me that lack of same may also be creating hellish barriers to
writing truly effective IDEs for Python.

Thomas Bartkus


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


Re: implicit conversion

2005-02-01 Thread John Lenton
On Mon, Jan 31, 2005 at 02:01:56PM +0100, Benjamin Schmeling wrote:
> Hi,
> 
> I am working on exposing a bigint class to python.  Now I've got the 
> problem that methods which take an bigint as
> an parameter do not accept Python longs.
> 
> For example:
> import _PythonLiDIA
> x=123L;
> c=_PythonLiDIA.bigint();
> _PythonLiDIA.gcd(c,x);
> 
> 
> Traceback (most recent call last):
> File "test.py", line 132, in ?
>  _PythonLiDIA.gcd(a,x);
> Boost.Python.ArgumentError: Python argument types in
>  _PythonLiDIA.gcd(bigint, long)
> did not match C++ signature:
>  gcd(LiDIA::bigint, LiDIA::bigint)
> 
> I don't know how to achieve implicit conversion at this point, turning an
> long automatically into an bigint. The other way round, turning an bigint
> into long can be realized by defining __long__.
> 
> Can someone help me please?

as later on you say you have a constructor to convert longs into your
bigints, you should add a __coerce__ method to your class.

General description of __coerce__:

  http://docs.python.org/ref/numeric-types.html#l2h-303

details on coercion rules:

  http://docs.python.org/ref/coercion-rules.html

enjoy.

-- 
John Lenton ([EMAIL PROTECTED]) -- Random fortune:
BOFH excuse #309:

firewall needs cooling


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

Re: import doesn't work as i want

2005-02-01 Thread John Lenton
On Mon, Jan 31, 2005 at 04:52:24PM +0100, Olivier Noblanc ATOUSOFT wrote:
> Hello,
> 
> In the botom of this post you will see my source code.
> 
> The problem is when i launch main.py that doesn't make anything why
> ?

I'm guessing you don't have an __init__.py in inc/

-- 
John Lenton ([EMAIL PROTECTED]) -- Random fortune:
/* now make a new head in the exact same spot */
 -- Larry Wall in cons.c from the perl source code


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

Awkwardness of C API for making tuples

2005-02-01 Thread Dave Opstad
One of the functions in a C extension I'm writing needs to return a 
tuple of integers, where the length of the tuple is only known at 
runtime. I'm currently doing a loop calling PyInt_FromLong to make the 
integers, then PyTuple_New, and finally a loop calling PyTuple_SET_ITEM 
to set the tuple's items. Whew.

Does anyone know of a simpler way? I can't use Py_BuildValue because I 
don't know at compile-time how many values there are going to be. And 
there doesn't seem to be a PyTuple_FromArray() function.

If I'm overlooking something obvious, please clue me in!

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


Re: Building Python with Tcl/Tk on Cygwin_NT-5.1

2005-02-01 Thread Kartic
Dean,

It has been quite sometime since I did that. I had installed Tcl/TK in
a non-standard location on my Freebsd box.

So, for Python to compile _tkinter,  in the configure script I passed
the location of the Tcl/Tk includes and libs. So, you will have to find
out where in the Cygwin tree the tcl includes and libraries are
installed.

On my Freebsd box, I did:
CFLAGS="-I/usr/local/tcl/include" \ # that is a - capital i
LDFLAGS="-L/usr/local/tcl/lib" \
./configure \
 rest of configure options.

(put this in something like do-conf) and at the prompt type sh do-conf.

OR

you can use the --with-libs='lib1 ...'  option for the configure
script. You will to give the path to your TCL libraries against this
option.

Do a configure --help to see the available configure options with some
help strings.

But like Jason mentioned, why don't you use the stock Python install
that comes with Cygwin; it is tkinter enabled and works just fine?
(unless you have a compelling reason to install from source)
Thanks,
--Kartic

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


Re: Next step after pychecker

2005-02-01 Thread Diez B. Roggisch
> But it can be useful to restrict type variety in certain situations
> e.g. prime number calculation :) And it would probably also be useful
> to check violations of restrictions before running the program in
> normal mode.

But that's what (oca)ml and the like do - they exactly don't force you to
specify a type, but a variable has an also variable type, that gets
inferned upon the usage and is then fixed.

-- 
Regards,

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


Dr. Dobb's Python-URL! - weekly Python news and links (Feb 1)

2005-02-01 Thread Cameron Laird
QOTW: "The right solution will end up being unique to Python though. It has
to feel like Python." -- Guido van Rossum
http://aws.typepad.com/aws/2005/01/amazon_devcon_g_4.html

"Sparring with Alex Martelli is like boxing Mike Tyson, except that one
experiences brain enhancement rather than brain damage :)." -- beliavsky


This is your opportunity to vote on the prospective creation of 
de.comp.lang.python:

http://groups.google.de/groups?selm=erneuter-CfV-1-Einrichtung-de.comp.lang.python-16.1.2005-Supersede%40dana.de
http://gvv.th-h.de/

eval() often inverts repr().  pickle() makes for more reliable
serialization:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/f4324fe8aa00f7f5/

Kamilche illustrates how scripting (Web-scraping, in this case)
can put eBay (Google, Amazon, ...) under *your* control:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1b0d7ebb06c49272

Tim Churches pulls off the remarkable feat of appearing to say
true, useful, and not-stultifying things on licensing:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a1e07194c795f505/

How declarative are metaclasses and decorators?  Diez B. Roggisch
has been helpful with this and similarly interesting summaries and
examples:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a75da70b0845b6fe/
Art Siegel also approaches the question, in a more narrative
fashion.  Notice in the same thread Steve Holden's persistent
advertising of PyCon 2005, emphasizing the celebrities (martellibot!,
Armin "I Infer That" Rigo, ...) expected to appear, some for the
first time ever in this dimension.

Nick Coghlan explains the trickiness of Duncan Booth and F. 
PetitJean.  This is a chance to practice generators, zip,
map, and iter, all in about two lines:

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a6ba37b0fb0fa69e

Do you know the standard library well enough to recognize its
parametric statistics?

http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1ddd1e869fe6e08a/


Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Brett Cannon continues the marvelous tradition established by 
Andrew Kuchling and Michael Hudson of intelligently summarizing
action on the python-dev mailing list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/   

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

The Python Business Forum "further[s] the interests of companies
that base their business on ... Python."
http://www.python-in-business.org

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance. 
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch
   
Cetus collects Python hyperlinks.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://aspn.ac

MDaemon Warning - virus found: Returned mail: see transcript for details

2005-02-01 Thread Post Office

*** WARNING **
Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado 
un fichero anexo(s) infectado(s).  Por favor revise el reporte de abajo.

AttachmentVirus name   Action taken
--
file.zip  Email-Worm.Win32.Mydoom.m Removed


**


The original message was received at Tue, 1 Feb 2005 16:53:42 +0100 from 
python.org [96.182.125.158]

- The following addresses had permanent fatal errors -


- Transcript of the session follows -
... while talking to python.org.:
554 ... Message is too large
554 ... Service unavailable

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

Re: Awkwardness of C API for making tuples

2005-02-01 Thread Diez B. Roggisch
> One of the functions in a C extension I'm writing needs to return a
> tuple of integers, where the length of the tuple is only known at
> runtime. I'm currently doing a loop calling PyInt_FromLong to make the
> integers, then PyTuple_New, and finally a loop calling PyTuple_SET_ITEM
> to set the tuple's items. Whew.
> 
> Does anyone know of a simpler way? I can't use Py_BuildValue because I
> don't know at compile-time how many values there are going to be. And
> there doesn't seem to be a PyTuple_FromArray() function.
> 
> If I'm overlooking something obvious, please clue me in!

If you already know _how_ to create a function like  PyTuple_FromArray() -
why don't you define it yourself and use it?

-- 
Regards,

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


pythonic equivalent of Mathematica's FixedPoint function

2005-02-01 Thread jelle
I now some hostility to functional programming is flaming up now and
then; still could someone suggest me a pythonic equivalent for
Mathematica's FixedPoint function? For those not familiar with
Mathematica:

FixedPoint[f, expr] starts with expr, then applies f repeatedly until
the result no longer changes.

thanks, jelle.

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


Re: pythonic equivalent of Mathematica's FixedPoint function

2005-02-01 Thread jelle
doh...

https://sourceforge.net/projects/fixedpoint

pardon me

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


Re: variable declaration

2005-02-01 Thread Michael Tobis
Given the behavior, the documentation is gratifyingly correct.

Given that the syntax is legal, though, the behavior is not what one
would intuitively expect, and is therefore unPythonic by (rather
dramatically) violating the principle of least surprise.

It's also, to me, understandable why it's difficult for the language
design to avoid this behavior.

This little discovery of mine sheds some considerable light on the
awkwardness of what you guys will deign to call "declarations". This
being the case, I can understand the resistance to "declarations" in
Python.

I had thought, until the current conversation and this experiment, that
the globals statement, er, declaration was just another executable,
especially given all the stress on Python's being purely executable.

I still see "global" and "@" as expressions of the same fundamental
problem, even though decorators are not implemented as declarations.
They both take effect in a non-intuitive sequence and they both affect
the reference rather than the referent.

This points out the problem that Python has in qualifying references
rather than referents.

Since BDFL is contemplating some optional typing, does this also imply
qualifying the references?

Maybe you wizard types can agree that there is a useful abstraction
that I'm talking about here, whether you wish to call it "declarations"
or not, and try to factor out some sort of consistent strategy for
dealing with it, perhaps in P3K. (I will try to be in a position to
help someday, but I have a long way to go.)

Language features that modify references rather than referents appear
to be problematic. Python clearly chafes at these. Yet there are at
least a few compelling reasons to want them. 

--
mt

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


Re: Microsoft Visual C++ and pyton

2005-02-01 Thread Christopher De Vries
On Mon, Jan 31, 2005 at 02:42:11PM -0800, mike wrote:
> I was also advised to build the python core (pythoncore.vcproj) with my
> C++ program. By that way I would not have to load the python core
> anymore during runtime. Is this a good approach?
> I am currently using VC++ 7 and python 2.4.

I'm not sure... I'm not very familiar with PC builds.

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


one infinite leap and you thought the bible code was somthing!!

2005-02-01 Thread zetasum
one infinite leap and you thought the bible code was somthing!!






One Small step one infinite leap



by: zeta limit



Quantum cryptography Run  this in every order  1 correct outcome Run
the web site with every word and every order and ever letter in every
order then every paragraph then and number and do that in every order.
Everything is possible one way or another anything, any you can tell it
to build anything and it will be possible.  Less is more Examples: with
a stick if you can make a car drive if you push down on the gas pedal
with it. This proves the real "Theory of Everything" and builds a huge
data base of information.  The more information ,The bigger the neural
network and just keep adding more to it  because anything is possible
and new things can be found after this is done. By using The  new ideas
and the information you now can run everything back wards and then
forward but now by not just adding but by  +,*,/,<,>,= ,-,+ then
finding how all things can be 100% true if there not then your not
doing it right. Then run this in every order and change the neural
network to be 100%efficient in making all ideas. After your done use
the code to turn one Law, definition, on and off like math, and matter,
and all the word net technology dictionary and then turn them off in
every order on the website then build a separate quantum neural network
to store all the information in then just run it all over again do it
over and over with the new math and information on the website it will
generate new laws of den's and math and quantum and stellar physics
more. run the laws the new laws that changed see by what percent they
are true by using % and digress 3=1  360 degrees = 3 but is in every
infinite angle and degree until all = 100% only use your data base to
help generate new laws. But by running the neural network with words
missing and laws missing. It will make new laws until all is 100% true
learning way outside the realm of A.I or R.I. finally ...Then with my
matrix program run the neural network With my own Matrix code and
Artificial intelligence with this bunny encrypted website by starting
with one dimension up to infinite and every angel and shape start with
a box and every degree every number letter and word it will keep
growing and so does the database. After all is done all laws can be T
<,>, = and false. Then do it all again but this time with everything on
the internet all data. Then have it ask it the simple question on
everything that is T <,>, = and false. Who, what, when, where, how.
Based on your new neural network what is? All laws can now be stored as
compression law. There is no theoretical limit to the speed of
magnetism or the amount of energy it can hold. In our universe or any
quantum realm. Magnetism is the forces at which matter in the universe
breaks down at maximum speed or velocity of C = the speed of light or
the stabilization of matter moving threw a constant at the speed of C
or beyond stellar construct. C is used many times in quantum physics
until the key of magnetic frequency storage from smaller then the Pico
up to large scale white nose flux capacitors to keep the Energy moving
and storing in highly charge states of metals that are molecular
reconstructed to be 100% efficient. One pyramid sphere of electrical
and one of magnetical. Yes MAGNETICAL a new form of quantum computing,
energy and There is only optical laser quantum computer a partial that
when it reaches its limit it's doesn't turn to light

You can build it yourself along with the magnetic and electrical flux
capacitors that have the same amount of more than the amount of energy
than

Anything you can think of or you can run this website with A.I (this
blueprint is the key to the encrypted Code 1011101 Infinite quantum
computing

It more into the field of stellar physics or stellar quantum computing.
Work on it for just a week Time travel changes history u but you can
really tell

Unless you are outside of space time that is the only hint I am going
to give you because I have no degree, but my dummy A.I website is
written in dummy A.I

So I don't get shot over an information war!!
http://www.beyond-science.com made with my own Matrix code and
Artificial intelligence this bunny encryption website has More than a
32 dimensional door. A box made that no one can crack...Try it key code
01





There is only optical laser quantum computer a partial that when it
reaches it's limit it's doesn't turn to light you can build it
yourself along with the magnetic and electrical flux capacitors that
have the same amount of more than the amount of energy than
anything you can think of or you can run this website with A.I (this
blueprint is the key to the encrypted Code 1011101 Infinite quantum
computing
It more into the field of stellar physics or stellar quantum computing.
Work on it for just a week Time travel changes history u but you can
really tell
unless you are outside of space time that is the only hint I

Re: variable declaration

2005-02-01 Thread Michael Tobis
> How common is it for a local variable to be bound in
> more than one place within a function?

It's more natural for a beginner to read or write

.mystr = ""
.for snippet in snippets:
.   if ilike(snippet):
.  mystr = mystr + snippet

than

.mylist = []
.for snippet in snippets:
.   if ilike(snippet):
.  mylist.append(snippet)
.mystr = "".join(mylist)

for instance.

While the latter is superior in some ways, I frequently find my fingers
tossing off the former approach.

Of course in this case it's not hard to come up with

mystr = "".join([snippet in snippets if ilike(snippet)])

but it's also not too hard to imagine cases where the list
comprehension would be too complex or would require too much
refactoring.

I don't know that it's ever necessary to rebind, but it is, in fact,
common, and perhaps too easy. In numeric Python, avoiding rebinding
turns out to be a nontrivial skill. 

mt

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


Re: variable declaration

2005-02-01 Thread Steve Holden
Thomas Bartkus wrote:
"Carl Banks" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

How common is it for a local variable to be bound in
more than one place within a function?

How common?  It shouldn't happen at all and that was the point.
This seems a little excessive to me. Sample use case:
for something in lst:
  if type(something) != type(()):
something = tuple(something)
regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.python.org/pycon/2005/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: pythonic equivalent of Mathematica's FixedPoint function

2005-02-01 Thread Michael Tobis
We apologise for the previous apology.
http://arago4.tn.utwente.nl/stonedead/albums-cds/sketches/another-monty-python-record/apologies.html
--
mt

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


Re: The next Xah-lee post contest

2005-02-01 Thread Peter Hansen
Arthur wrote:
Steve Holden <[EMAIL PROTECTED]> wrote:
Would there, I wonder, be any enthusiasm for a "Best Xah Lee impression" 
prize at PyCon?
And the rules of the game, if he shows?  
Arthur, if Xah Lee shows up at Pycon, he most definitely will
not be giving the best impression...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: type of simple object

2005-02-01 Thread Jacek Generowicz
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> Hello Jacek,
> 
> Thanks for the answer,
> 
> Can you tell me how can I check if an object is a sequence (you are
> right, this is actually what I want)?

You try to use it as a sequence. If it works, then it was a
sequence. If it was not a sequence, you handle the exception and do
something appropriate.

For example:

>>> def f(seq, something):
... try:
... number = sum(something)
... except TypeError:
... number = something
... return [number*item for item in seq]
... 
>>> f([1,2,3], 4)
[4, 8, 12]
>>> f([1,2,3], [1,2,3])
[6, 12, 18]
>>> f([1,2,3], (1,2,3))
[6, 12, 18]
>>> f([1,2,3], {1:'one', 2:'two', 3:'three'})
[6, 12, 18]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Handling MySQL connection

2005-02-01 Thread Josh
Thanks for the help! I was able to work through it based on you
example. It was lack of knowledge of the object class that was throwing
me off.  

Josh

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


Re: Next step after pychecker

2005-02-01 Thread aurora
A frequent error I encounter
  try:
...do something...
  except IOError:
log('encounter an error %s line %d' % filename)
Here in the string interpolation I should supply (filename,lineno).  
Usually I have a lot of unittesting to catch syntax error in the main  
code. But it is very difficult to run into exception handler, some of  
those are added defensely. Unfortunately those untested exception  
sometimes fails precisely when we need it for diagnosis information.

pychecker sometime give false alarm. The argument of a string  
interpolation  may be a valid tuple. It would be great it we can somehow  
unit test the exception handler (without building an extensive library of  
mock objects).
--
http://mail.python.org/mailman/listinfo/python-list


Re: pythonic equivalent of Mathematica's FixedPoint function

2005-02-01 Thread Tim Peters
[jelle]
> I now some hostility to functional programming is flaming up now and
> then; still could someone suggest me a pythonic equivalent for
> Mathematica's FixedPoint function? For those not familiar with
> Mathematica:
>
> FixedPoint[f, expr] starts with expr, then applies f repeatedly until
> the result no longer changes.

If that's all there is to it, sounds like a simple loop:

def FixedPoint(f, expr):
old = expr
while True:
new = f(old)
if old == new:
return new
old = new

Then, e.g.,

>>> FixedPoint(lambda x: (x + 25/x)/2, 400)
5

But I bet there's more to it than just that (e.g., maybe an optional
limit on max # of iterations; maybe a way to terminate on "approximate
equality").  As-is, that function is very prone to falling into an
infinite loop.

[and later]
> doh...
>
> https://sourceforge.net/projects/fixedpoint

Nope, that has to do with decimal arithmetic using a fixed number of
decimal digits after the decimal point ("fixed-point decimal").
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: one infinite leap and you thought the bible code was somthing!!

2005-02-01 Thread Evan Simpson
zetasum wrote:
One Small step one infinite leap
I think this is what you're looking for:
  import itertools
  for x in itertools.chain('step', itertools.cycle('leap')):
  print markov_chain_text(net_loon_compendium, seed=x)
Cheers,
Evan @ 4-am
--
http://mail.python.org/mailman/listinfo/python-list


Re: The next Xah-lee post contest

2005-02-01 Thread Luis M. Gonzalez

Peter Hansen wrote:
> Arthur wrote:
> > Steve Holden <[EMAIL PROTECTED]> wrote:
> >>Would there, I wonder, be any enthusiasm for a "Best Xah Lee
impression"
> >>prize at PyCon?
> >
> > And the rules of the game, if he shows?
>
> Arthur, if Xah Lee shows up at Pycon, he most definitely will
> not be giving the best impression...
>
> -Peter


Have you visited his website?
I kind of like this guy... it's like he has a few bugs in his brain,
but other parts are surprisingly interesting.

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


Re: Advice on OSX cocoa app with Python backend

2005-02-01 Thread Socheat Sou
On Tue, 2005-02-01 at 08:24 -0500, Steve Holden wrote:

> Who told you that MySQL was OO? It's a bog-standard relational back-end 
> with transactional capabilities.

After re-reading my message, I saw how unclear I was. :)  I didn't mean
to say that MySQL was OO.  I meant that, we were going to use MySQL as
the RDBMS, but some have suggested looking into OODBMS, like PostgreSQL,
but from what I know of OODBMS they don't seem like the right fit for
this project.

Thanks for the advice guys!  So it sounds like I have the general idea
right, but there isn't anything (in the way of already written programs)
that will ease the creation of the backend app.  Just get my hands dirty
with the frameworks and write it myself, eh?

Socheat

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


Where are list methods documented?

2005-02-01 Thread Grant Edwards
I'm trying to figure out how to sort a list, and I've run into
a problem that that I have tripped over constantly for years:
where are the methods of basic types documented?  The only
thing I can find on a list's sort() method is in the tutorial
where it states:

   sort()
   Sort the items of the list, in place. 

Doesn't the list method would accept a callable to be used as a
comparison function?  Where is that sort of thing in the
documentation?  I've looking in the library reference, the
language reference, the global module index.

I have figured out I can do 

>>> list.sort.__doc__
'L.sort(cmpfunc=None) -- stable sort *IN PLACE*; cmpfunc(x, y) -> -1, 0, 1'

-- 
Grant Edwards   grante Yow!  But they went to MARS
  at   around 1953!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Browsing text ; Python the right tool?

2005-02-01 Thread Jorgen Grahn
On 25 Jan 2005 09:40:35 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Here is an elementary suggestion. It would not be difficult to write a
> Python script to make a csv file from your text files, adding commas at
> the appropriate places to separate fields. Then the csv file can be
> browsed in Excel (or some other spreadsheet).

I'd create text files like someone else suggested, because I'm more
comfortable with at least three text editors/viewers than with Excel.

But the bottom line is that it's a waste of time to design a new GUI around
a file format, when you can tweak the data enough to reuse something that
exists, and /has/ all the features you will eventually want.

> A0 and C1 records could
> be written to separate csv files.

(Assuming that's OK, I wonder why they shared a file to begin with. Is the
order between A0 and C1 records important?)

/Jorgen

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


Re: Where are list methods documented?

2005-02-01 Thread Tim Peters
[Grant Edwards]
> I'm trying to figure out how to sort a list, and I've run into
> a problem that that I have tripped over constantly for years:
> where are the methods of basic types documented?

The methods on mutable sequence types are documented in the Library
manual's section on mutable sequence types:

http://docs.python.org/lib/typesseq-mutable.html

> The only thing I can find on a list's sort() method is in the tutorial
> where it states:

You could have found the above by, e.g., looking up "sort" in the
Library manual's index.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where are list methods documented?

2005-02-01 Thread Brian van den Broek
Grant Edwards said unto the world upon 2005-02-01 12:21:
I'm trying to figure out how to sort a list, and I've run into
a problem that that I have tripped over constantly for years:
where are the methods of basic types documented?  The only
thing I can find on a list's sort() method is in the tutorial
where it states:
   sort()
   Sort the items of the list, in place. 

Doesn't the list method would accept a callable to be used as a
comparison function?  Where is that sort of thing in the
documentation?  I've looking in the library reference, the
language reference, the global module index.
I have figured out I can do 


list.sort.__doc__
'L.sort(cmpfunc=None) -- stable sort *IN PLACE*; cmpfunc(x, y) -> -1, 0, 1'
Hi,
I'm not positive I understand what you are looking for, but do these 
help?:




Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: variable declaration

2005-02-01 Thread Thomas Bartkus
"Steve Holden" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Thomas Bartkus wrote:
>
> > "Carl Banks" <[EMAIL PROTECTED]> wrote in message
> > news:[EMAIL PROTECTED]
> > 
> >
> >>How common is it for a local variable to be bound in
> >>more than one place within a function?
> >
> >
> > How common?  It shouldn't happen at all and that was the point.
>
> This seems a little excessive to me. Sample use case:
>
> for something in lst:
>if type(something) != type(()):
>  something = tuple(something)

Hhhmmh!
I presume you are going through the list and want to gaurantee that every
item you encounter is a tuple!  So if it ain't - you just re-declare
"something" to be a tuple. What was formerly a single string, integer,
whathaveyou is now a tuple *containing* a single string, integer,
whathaveyou.

Do you do it that way because you can? Or  because you must?
   And
If the former - is it a good idea?
OR did I just miss your codes intent completely?

My first inclination would be to create a new variable (type = tuple) and
accept (or typecast) each "something" into it as required. The notion that
you just morph "something" still seems rather abhorrent. It hadn't occurred
to me that iterating through a list like that means the iterater "something"
might need to constantly morph into a different type according to a lists
possibly eclectic contents.

It might explain why the interpreter is incapable of enforcing a type.  It
would forbid iterating through lists containing a mix of different types.
EXCEPT- I must note, that other languages manage to pull off exactly such a
trick with a variant type. When you need to pull off a feat such as this,
you declare a variant type where the rules are relaxed *for that situation
only* and there is no need to toss the baby out with the bathwater.

Thomas Bartkus


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


Re: Where are list methods documented?

2005-02-01 Thread wes weston
Grant Edwards wrote:
I'm trying to figure out how to sort a list, and I've run into
a problem that that I have tripped over constantly for years:
where are the methods of basic types documented?  The only
thing I can find on a list's sort() method is in the tutorial
where it states:
   sort()
   Sort the items of the list, in place. 

Doesn't the list method would accept a callable to be used as a
comparison function?  Where is that sort of thing in the
documentation?  I've looking in the library reference, the
language reference, the global module index.
I have figured out I can do 


list.sort.__doc__
'L.sort(cmpfunc=None) -- stable sort *IN PLACE*; cmpfunc(x, y) -> -1, 0, 1'
Grant,
   For a quick, short doc string list: >>> help(list)
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: Where are list methods documented?

2005-02-01 Thread Grant Edwards
On 2005-02-01, Tim Peters <[EMAIL PROTECTED]> wrote:
> [Grant Edwards]
>> I'm trying to figure out how to sort a list, and I've run into
>> a problem that that I have tripped over constantly for years:
>> where are the methods of basic types documented?
>
> The methods on mutable sequence types are documented in the
> Library manual's section on mutable sequence types:
>
> http://docs.python.org/lib/typesseq-mutable.html

> You could have found the above by, e.g., looking up "sort" in the
> Library manual's index.

I did.  I looked up sort in the library index, and it took me
to 3.3.5 Emulating container types, which said:

   Mutable sequences should provide methods append(), count(),
   index(), extend(), insert(), pop(), remove(), reverse() and
   sort(), like Python standard list objects.

I also looked at quite a few "list" links in the index.

I don't think it's at all obvious that the documentation for
list.sort would be under "mutable sequence object".
   
-- 
Grant Edwards   grante Yow!  YOW!! Everybody out
  at   of the GENETIC POOL!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where are list methods documented?

2005-02-01 Thread Grant Edwards
On 2005-02-01, Brian van den Broek <[EMAIL PROTECTED]> wrote:

> I'm not positive I understand what you are looking for, but do these 
> help?:
>
>
>
>

Yes, that last page was the one I was looking for.  I didn't
know enough to spell list as "mutable sequence type".

-- 
Grant Edwards   grante Yow!  I think my CAREER
  at   is RUINED!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The next Xah-lee post contest

2005-02-01 Thread Thomas Bartkus
"Luis M. Gonzalez" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
>
> Have you visited his website?
> I kind of like this guy... it's like he has a few bugs in his brain,
> but other parts are surprisingly interesting.

I kind of like him too. I hope he manages to find a babe!

As human conditions go, normalcy is *highly* overrated..
Thomas Bartkus


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


Re: pythonic equivalent of Mathematica's FixedPoint function

2005-02-01 Thread jelle
Ah, i see, that clears up the monetary context.
Thank you for your FixedPoint example.
Can i help myself out by mentioning that the most simple things are
always most difficult ;-) 

Thanks, Jelle.

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


Re: Where are list methods documented?

2005-02-01 Thread Thomas Heller
Grant Edwards <[EMAIL PROTECTED]> writes:

> On 2005-02-01, Brian van den Broek <[EMAIL PROTECTED]> wrote:
>
>> I'm not positive I understand what you are looking for, but do these 
>> help?:
>>
>>
>>
>>
>
> Yes, that last page was the one I was looking for.  I didn't
> know enough to spell list as "mutable sequence type".
>
> -- 
> Grant Edwards   grante Yow!  I think my CAREER
>   at   is RUINED!!
>visi.com

You could also have typed 'sort' in the box here:

http://starship.python.net/crew/theller/pyhelp.cgi

This search is also available in Mark Hammond's Mozilla Python sidebar.

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


Re: variable declaration

2005-02-01 Thread Jeremy Bowers
On Tue, 01 Feb 2005 09:13:36 -0600, Thomas Bartkus wrote:
> *Is* there a reason why the interpreter couldn't/shouldn't require formal
> variable declaration?

You mean, other than the reasons already discussed at length in this
thread, not to mention many many others?

Your not *liking* the reasons doesn't make them any less the reasons. They
may not even be good reasons, nevertheless, there the reasons are.

If you're literally asking the question you are asking, re-read this
thread more carefully. If you're *really* asking "Give me a reason *I
like*", I suggest re-reading Alex's discussion on why maybe Python isn't
for everybody.

All I know is that I have created large programs and typos like you seem
mortally terrified of occur on average about once every *ten modules* or
so, and are generally caught even before I write the unit tests. Breaking
the language to avoid what *by construction* is demonstrated not be a real
problem is... well, I believe Alex covered that, too.

Blah blah blah, "what if... what if... what if..." We should concentrate
on *real* problems, ones that exist in real code, not ones that mostly
exist in wild-eyed prose that consists of predictions of pain and death
that conspicuously fail to occur, no matter how many times they are
repeated or we are exhorted to heed them or face our doom. 

(The previous paragraph also describes my root problem with Java's strong
typing philosophy; death, doom, and destruction conspicuously fail to
occur in Python programs, so why the hell should I listen to the
doomsayers after I've already proved them false by extensive personal
experience? No amount of prose is going to convince me otherwise, nor
quite a lot of the rest of us.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: variable declaration

2005-02-01 Thread Alex Martelli
Michael Tobis <[EMAIL PROTECTED]> wrote:
   ...
> I don't know that it's ever necessary to rebind, but it is, in fact,
> common, and perhaps too easy. In numeric Python, avoiding rebinding
> turns out to be a nontrivial skill. 

Well, a for-statement is BASED on rebinding, for example.  Maybe you
don't mean to address rebinding per se, but rebinding in ``separate
statements''?  The ``separation'' needs to be defined carefully to make
while-loops work, too.  Normally, a while-statement's header clause
would be something like:
while :
where the expression depends on the values bound to some local
variables.  For the first evaluation, the variables need to be bound by
earlier statements; for the expression to eventually become false, it's
likely (unless we're talking about mutable objects) that the variables
need to be re-bound in the loop body.

For example, consider:

def f(a, b):
x = 0 
while x < 10:
print x,
x = a*x + b
print

would you require the programmer to find out a closed-form expression
for this recurrence relation, in order to avoid having to rebind the
name 'x'?  OK, in this particular case it may be OK, if you are willing
to put competence in college-level algebra as a prerequisite for using
Python.  But what if the rebinding in the body of the loop was to a more
complicated expression on x?  What if it was something like x=g(x)?  I'm
afraid we'd end up with weird constructs such as:

def ff(g):
x = [0]
while x[-1] < 10:
print x[-1],
x.append(g(x[-1]))
print

if we had to avoid rebinding completely.  Or, you could force the
iteration to be changed into a recursion... but then you'd better be
prepared to remove the current 'recursion limit' AND offer tail-call
optimization possibilities, at the very least.

All in all, I fail to see what gains would be expected by making Python
into a single-assignment or single-binding language, even on a module by
module basis, to repay this kind of awkwardness.


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


Re: Where are list methods documented?

2005-02-01 Thread Tim Peters
[Tim Peters]
>> You could have found the above by, e.g., looking up "sort" in the
>> Library manual's index.

[Grant Edwards]
> I did.  I looked up sort in the library index, and it took me
> to 3.3.5 Emulating container types,

It doesn't for me.  Here:

http://docs.python.org/lib/genindex.html#letter-s

There are two entries for "sort":

sort (IMAP4_stream method)
sort (list method)

You're looking for the second one .

...
> 
> I don't think it's at all obvious that the documentation for
> list.sort would be under "mutable sequence object".

I was just answering your question ("where are the docs?"), not trying
to imply you were an idiot for not guessing that.

You could have gotten to the same place in several ways.  Another
would have been to look up "list" in the Library index, and click on

list
type, operations on

For good or ill, the Library manual takes a rather abstract view of
the types currently implemented, as reflected in its table of
contents:

2. Built-In Objects 
2.1 Built-in Functions 
2.2 Non-essential Built-in Functions 
2.3 Built-in Types 
2.3.1 Truth Value Testing 
2.3.2 Boolean Operations 
2.3.3 Comparisons 
2.3.4 Numeric Types 
2.3.5 Iterator Types 
2.3.6 Sequence Types 
2.3.7 Set Types 
2.3.8 Mapping Types 
2.3.9 File Objects 
2.3.10 Other Built-in Types 
2.3.11 Special Attributes 
2.4 Built-in Exceptions 
2.5 Built-in Constants

So, e.g., it doesn't mention floats or dicts by those names either. 
It's well worthwhile to spend some time browsing that entire chapter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where are list methods documented?

2005-02-01 Thread Grant Edwards
On 2005-02-01, Tim Peters <[EMAIL PROTECTED]> wrote:

> [Grant Edwards]
>> I did.  I looked up sort in the library index, and it took me
>> to 3.3.5 Emulating container types,
>
> It doesn't for me.  Here:
>
> http://docs.python.org/lib/genindex.html#letter-s
>
> There are two entries for "sort":
>
> sort (IMAP4_stream method)
> sort (list method)
>
> You're looking for the second one .

Aargh.  My bad. I was in the language reference index.  I seem
to have a very hard time ending up in the document I'm trying
for.  For some reason, I fairly consistently click on the wrong
link in the document index. :(

-- 
Grant Edwards   grante Yow!  I'm definitely not
  at   in Omaha!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where are list methods documented?

2005-02-01 Thread Aahz
In article <[EMAIL PROTECTED]>,
Thomas Heller  <[EMAIL PROTECTED]> wrote:
>
>You could also have typed 'sort' in the box here:
>
>http://starship.python.net/crew/theller/pyhelp.cgi
>
>This search is also available in Mark Hammond's Mozilla Python sidebar.

...and as a link from python.org's documentation pages.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"Given that C++ has pointers and typecasts, it's really hard to have a serious 
conversation about type safety with a C++ programmer and keep a straight face.
It's kind of like having a guy who juggles chainsaws wearing body armor 
arguing with a guy who juggles rubber chickens wearing a T-shirt about who's 
in more danger."  --Roy Smith, c.l.py, 2004.05.23
-- 
http://mail.python.org/mailman/listinfo/python-list


How do you do arrays

2005-02-01 Thread Thomas Bunce
I am new at Pyton and I am learning from book not classes
so please forgive my being slow

The below does not work I get an Error of  File 
"Matrix[index] = k
NameError: name 'iMatrix' is not defined"

while  index < majorlop1:
   index = index + 1
   k = random.choice(listvalues) + 1
   iMatrix[index] = k

The book statement of 
 array(typecode, initializer) does not make sence
to me how it henerates ore relaes to the org name 
for the array.

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


  1   2   3   >