Good use for Jython

2005-03-16 Thread Mike Wimpe
Other than being used to wrap Java classes, what other real use is
there for Jython being that Python has many other GUI toolkits
available? Also, these toolkits like Tkinter are so much better for
client usage (and faster) than Swing, so what would be the advantage
for using Jython? or Is Jython really just so that Java developers can
write Java code faster?

Mike Wimpe

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


Re: Why tuple with one item is no tuple

2005-03-16 Thread Tim Roberts
Gregor Horvath [EMAIL PROTECTED] wrote:

 type(['1'])
type 'list'

 type(('1'))
type 'str'

I wonder why ('1') is no tuple

There were lots of answers, but I'm not sure I saw the why addressed.

Consider this:

a = (3 + 5) * 5

You really, really want (3 + 5) to be an integer, not a one-item tuple.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza  Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python becoming less Lisp-like

2005-03-16 Thread Peter Maas
Fernando schrieb:
The real problem with Python is that it has been very successful as a
scripting language in the static-typing/C/C++ world. Those
programmers, instead of adapting their evil ways to Python, and
realizing the advantages of a dynamic language, are influencing
Python's design and forcing it into the static-typing mold.
Examples?
Python is going the C++ way: piling feature upon feature, adding bells
and whistles while ignoring or damaging its core design.
What is core design? What are bells and whistles? I find it surprising
that you talk about adding bells and whistles, whereas the URL you are
referring to is about removing features.
The new 'perlified' syntax for decorators, the new static type bonds
and the weird decision to kill lambda instead of fixing it are good
examples that show that Python is going the wrong way.
I don't think that the introduction of '@' for decorators justifies
the term perlification. If special characters are avoided at all costs
Python could become too verbose like Java which is often critized for
that in c.l.py.
What used to be a cool language will soon be an interpreted C/C++
without any redeeming value. A real pity...
What do you mean with cool? Which parts of Python are C/C++ish? Which
features leave Python without any redeeming value? This phrase
is close to trolling because is vague, emotional and unspecific.
The fear of the anti-static fanatics is unfounded. Guido has made
clear that he is thinking of a  pychecker-like mechanism for
validating programs at compile time. There's nothing wrong with
defining interfaces and conditions and being able to check them
before actually running the program.
--
---
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


iterable terminology (for language lawyers)

2005-03-16 Thread Michele Simionato
According to the standand library
(http://docs.python.org/lib/typeiter.html)
an *iterable* is something with an __iter__ method. This means that
strings
are *not* iterable. However I can loop over a string without problem
and I would
say that an iterable is anything I can iterate over. Of course I am
*not* proposing
we add __iter__ to strings (it is convenient for me to be able to
distinguish
strings from other iterables, since more often than not a string
wants to
be treated as an atomic object). The reason why I ask for a
clarification is
that I am going to give a course at the ACCU conference, so I want to
make
sure I use the rigth terminology.

   Michele Simionato

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


Re: SAX parsing problem

2005-03-16 Thread gh
In article [EMAIL PROTECTED], David M.
Cooke [EMAIL PROTECTED] wrote:

 anon [EMAIL PROTECTED] writes:
 
  So I've encountered a strange behavior that I'm hoping someone can fill
  me in on.  i've written a simple handler that works with one small
  exception, when the parser encounters a line with '#38;' in it, it
  only returns the portion that follows the occurence.  
 
  For example, parsing a file with the line :
  keymykey/keyvaluesome%20#38;%20value/value
 
  results in getting %20value back from the characters method, rather
  than some%20#38;%20value.
 
  After looking into this a bit, I found that SAX supports entities and
  that it is probably believing the #38; to be an entity and processing
  it in some way that i'm unware of.  I'm using the default
  EntityResolver.
 
 Are you sure you're not actually getting three chunks: some%20, ,
 and %20value? The xml.sax.handler.ContentHandler.characters method
 (which I presume you're using for SAX, as you don't mention!) is not
 guaranteed to get all contiguous character data in one call. Also check
 if .skippedEntity() methods are firing.

Ya,  skippedEntity() wasn't firing, but you are correct about receiving
three chunks.  The characters handler routine is fired 3 times for a
single text block.  Why does it do this?  Is there a way to prevent
doing this? 

Much thanks.

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


Re: __getitem__ method on (meta)classes

2005-03-16 Thread Steven Bethard
Steven Bethard wrote:
py class enum(object):
... class item(object):
... def __init__(self, val):
... self.val = val
... def __repr__(self):
... return 'enum.item(%r)' % self.val
... def __init__(self, vals):
... self.items = [type(self).item(val) for val in vals]
... self._val_item_map = dict(zip(vals, self.items))
... self._index_item_map = dict(enumerate(self.items))
Sorry, this was before I decided I should save items as an instance 
variable.  Drop this map, it's unnecessary.

... def __call__(self, val):
... try:
... return self._val_item_map[val]
... except KeyError:
... raise TypeError(%s is not a valid %s % (val, type(self)))
... def __getitem__(self, index):
... return self._index_item_map[index]
And replace this with self.items[index]
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Itertools wishlists

2005-03-16 Thread TZOTZIOY
On Sun, 13 Mar 2005 06:52:40 GMT, rumours say that Raymond Hettinger
[EMAIL PROTECTED] might have written:

[snip of lots of stuff]

itertools.window() with n=2 got rejected.  Almost all proposed uses had better
solutions (such as an accumulator variable or fibonacci sequence style logic:
a, b = b, a+b).  Writing it in C afforded only small speed advantage over a
solution using izip() and tee().

Speed or C implementation was not my objection.  I don't care if C itertools
gets renamed to _itertools and some Python itertools imports _itertools first
thing a la heapq, and then the most probably useful doc recipes get defined in
Python; in fact, I would like that.  Do you think that window is rarely used?
You didn't say that in your post, you just argued against implementing it in C.
I agree.  Don't implement it in C.  Implement it as in the recipe.  Just make it
readily available.  I volunteer for a patch if we agree on it[1].

For example, if speed is our main concern, why is there PEP 309 for partial
function application as a class?  The tools are already there, and
new.instancemethod is our friend.  In the case of binding only the first
argument, which is the most common, calling the resulting object is 2% faster
than calling the function itself (at least on my laptop).  Of course, PEP 309 is
not about speed; it's about availability of /correct/ and /useful/
functionality.  Kind of like recipes in the itertools documentation.

'nuff said, mister whatever happened to batteries included ;-)

Cool extensive summarising reply --however, how relevant is it?  None of the
itertools.(queue|roundrobin|accumulate|multi_gen|remove_value|eq|consume|ilines)
that you reference exists as a recipe in the docs.

Did I make you believe I cared about the fate of any function judged unworthy
even for the documentation?  Because, if it is my fault, let me correct that: I
am talking about the recipes in the documentation (those found worthy enough to
be included in the docs, but not found worthy enough to be included in the lib),
and specifically for window and flatten: why aren't they considered as
batteries?  About flatten, you say things are still warm.  About window, you say
it's not really efficient, use izip and tee, or use a deque for n2.  Ok.  I
never spoke about speed.  I spoke about tool availability.

IIRC you were cooled down in Python-Dev from adding more functions into
itertools; it was kind of a surprise for me now to see /you/ of all people
defending this choice.  FWIW, I like speed (who doesn't if nothing else is
affected?); I have an unpolished CPython pcode decompiler / compiler that offers
a decorator for function-level optimising and a function that modifies *.py[co]
files replacing patterns like the one you yourself lately worried about [2],
which module I leave as-is partly waiting the AST branch to be finished and
partly because now and then you implement some part of it in the peephole
optimiser.  So no objections about speed, just note that I didn't mention it in
my previous post.

AFAIAC, in my own stdlib-supporting modules what I need is readily available;
possibly I'm just whining that putting recipes in the docs as an 'extended
toolset' instead of in a module is a joking compromise...

P.S.  It's not an accident that the recipes in the itertools docs are in a form
that is directly cut and pastable into a working application.

[1] Like I said, I volunteer to copy-paste from the docs into a Python module
for the stdlib.  Thanks for the eye-opening hint!-)

[2] STORE_sth x/LOAD_sth x into DUP/STORE_sth x, local binding of multiple
LOAD_sth x/LOAD_ATTR/LOAD_ATTR where x is an imported module into a LOAD_FAST or
a LOAD_CONST based on whether it's the modifier or the decorator,
LOAD_CONST*/BUILD_LIST into LOAD_CONST a_tuple/UNPACK_SEQUENCE/BUILD_TUPLE,
a,b,c=d,e,f reordering and dropping of the tuple building/unpacking (which is
a case already improved in C) etc.
-- 
TZOTZIOY, I speak England very best.
Be strict when sending and tolerant when receiving. (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code for Computer Language Shootout

2005-03-16 Thread F. Petitjean
Le Tue, 15 Mar 2005 23:21:02 -0800, Michael Spencer a écrit :
 Jacob Lee wrote:
 On Tue, 15 Mar 2005 21:38:48 -0800, Michael Spencer wrote:
 
 Good call.
 
 
 
 How about this then:
 
 basetable = string.maketrans('ACBDGHKMNSRUTWVYacbdghkmnsrutwvy',
   'TGVHCDMKNSYAAWBRTGVHCDMKNSYAAWBR')
 
 from collections import deque
 from itertools import islice
 
 def output(seq, linelength = 60):
  if seq:
  iterseq = iter(seq)
  while iterseq:
  print .join(islice(iterseq,linelength))
I suppose you mean :
   print .join( str(item) for item in islice(iterseq, linelength) )
   #  using python 2.4 genexp
 
 def revcomp(input = sys.stdin):
  seqlines = deque()
  for line in input:
  if line[0] in ;:
  output(seqlines)
  print line,
  seqlines.clear()
  else:
  seqlines.extendleft(line.translate(basetable, \n\r))
  output(seqlines)
 
 
 It would be nice to inline the output function, and re-arrange the iteration 
 so 
 that EOF triggers the same suite as line[0] in ;
 
 Michael
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Minidom empty script element bug

2005-03-16 Thread Martin v. Löwis
Derek Basch wrote:
maybe you meant createTextNode?
Yes, that's what I meant :-)
However, it seems proper that XHTMLPrinter (or some other module)
should allow the developer to use either normative or non-normative
XHTML design guidlines to achieve some sane degree of HTML user agent
compatablilty.
This is now PyXML, right? I also maintain PyXML...
Yes, XHtmlPrinter would be the right place to deal with XHTML
idiosyncrasies.
Anyways, thanks for the help again and feel free to shoot down my
suggestions :)
The general approach sounds good; feel free to submit a patch
to sf.net/projects/pyxml. I would recommend to implement Annex C
to the letter, i.e. only avoid the minimized form if the content
model is not EMPTY.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


RE: Good use for Jython

2005-03-16 Thread Tertius Cronje
 Other than being used to wrap Java classes, what other real use is
 there for Jython being that Python has many other GUI toolkits
 available? Also, these toolkits like Tkinter are so much better for
 client usage (and faster) than Swing, so what would be the advantage
 for using Jython? or Is Jython really just so that Java developers can
 write Java code faster?
 

Just as many on this list, my favorite development
tool/language/environment is Python. However as nice as it is, there are
many frameworks and business applications that is written and packaged
in Java (i.e. X25 comms Libraries, log4J *before* python brought out
logging) _OR_ has a Java remote interface that must be accessed (EJB
/JMS / RMI etc...) _OR_ has a library you prefer to use of over the
python implementation (not a lot of those).

Jython allows one to use these packages using ones language of choice :)

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


Re: unicode converting

2005-03-16 Thread Maxim Kasimov
Christos TZOTZIOY Georgiou wrote:
If unicode_data references your unicode data, all you have to send is:
unicode_data.encode('utf-16') # maybe utf-16be for network order
is utf-16 string the same ucs-2? my question is how to get string encoded as 
UCS-2
--
Best regards,
Maxim
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python becoming less Lisp-like

2005-03-16 Thread Paul Boddie
Steven Bethard [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]...
 
 Certainly descriptors in the wrong hands could lead to confusing, 
 unreadable code.  But Python is a we're all adults here language, and 
 so we have to trust other coders to be responsible.

The problem is as much about social dynamics as it is about
responsibility. Introduce a cool new feature and there'll always be a
minority who will use it in every situation, no matter how absurd; the
problem arises when these unnecessary excursions into absurdity start
to dominate the code you're using or maintaining.

  There are some very 
 reasonable uses for descriptors which I don't believe are really 
 confusing, for example the lazy property recipe:
 
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/363602

This is all very exciting, but...

  * You could do this with __getattr__ since Python 1.x, possibly
even Python 0.x. Moreover, the __getattr__ example would be
more readable.

  * This introduces runtime baggage to solve a notation issue. Yes,
accessor methods are so Java, but once a program is running
who cares whether it's a property or a method that is getting
called? (Actually, for interactive inspection of an object
model there is some argument for having properties...)

I think the first point quite reasonably illustrates the original
contributor's concerns about Python's current consistency/coherency.

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


Super job openings for Python users with MNC in B'LORE with onsite opportunities

2005-03-16 Thread nid2000kick

Hi all ,

I am Nidhi Shetty representing Quadrangle, Bangalore, a recruitment
firm in Bangalore and this mail is to inform you guys of a very good
job opening with one of my MNC clients .

About the client :
They are one of the biggest software company's in the world .Their
products are of worldwide repute .

The job description is as follows :
Skills  Qualifications required:
• Excellent written  verbal communication, presentation, and
interpersonal skills. Ability to communicate complex problems and
solution proposals in a non-technical manner.
• Working time flexibility for real-time collaboration across time
zones.


Education / Experience
o B.A. / B.S. in information systems, Computer Science or related
field from a four year institution; Masters preferred.
o 3+ years of commercial software engineering experience or an
equivalent combination of education and experience.

Programming skills
o Strong Python Skills (2+ years experience)
o Very good C/C++ skills
o Unix skills including shell scripting, bash and/or ksh
o Knowledge of Windows technologies – particularly COM
o ClearCase commandline experience
o Knowledge of MSI

Technical Leadership
o Can facilitate requirements collection from several groups
o Document these requirements
o Create a realistic schedule to meet those requirements

Software Engineering
o Ability to debug issues (Code, Scripting, Install)
o Familiarity with configuration management

Ability to travel to the US for brief periods (Visa status)

Position Statement: For Candidate
This position requires a deep knowledge of software engineering in
order to facilitate the creation of custom integration tools for my
client's DCS lab.

   Incase you are interested in this opportunity ,  send me your
updated profile in word format asap kindly mention PYTHON in the
subject line of the mail .Should you need any clarification in this
regard feel free to call me on 9880141095 // 080- 25092231.
   Please do a good turn by forwarding this mail to any of your
friends or colleagues who would like to explore this opportunity .

   Thanks and Regards,
   Ms. Nidhi Shetty,
   Quadrangle -IT(A Division of Info Edge India(P)Ltd,
   S-305,
   Manipal Centre,
   Dickenson Road.
   Bangalore.
   Ph:080-25092231/25092074






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


Re: iterable terminology (for language lawyers)

2005-03-16 Thread Leif K-Brooks
Michele Simionato wrote:
According to the standand library 
(http://docs.python.org/lib/typeiter.html) an *iterable* is something
with an __iter__ method. This means that strings are *not* iterable.
In general, the definitions people in the Python community tend to use are:
Iterable: An object which doesn't raise TypeError when passed to iter().
Reiterable: An object which can be passed to iter() multiple times 
without returning itself.
Iterator: An object which defines a next() method and returns itself 
when passed to iter().
--
http://mail.python.org/mailman/listinfo/python-list


{SPAM} Remote debugging

2005-03-16 Thread Gijs Korremans
Hi,

For developing Python 2.3 applications I use Boa Constructor for debugging the 
application. This is working fine but now I want to debug an application on a 
remote PC (win 2003 server) installed as a NT Service. I know it is possible 
with Boa Constructor and HAP debugger but it doesn’t work with both debuggers.

With the HAP debugger it is possible to connect to the remote pc but it doesn’t 
stop at the breakpoints

The Boa Constructor doesn’t work at all, when I go to Tools-Attach to debugger 
and press Ok I get the error message “error: (10061, ‘Connection refused’)” 
I followed the steps in Boa Debugger help and every thing I found on google: 
Add the debugger to Zope.

I’ve installed the source code on the same place at the server and at the 
client pc (D:\project\)

Does anybody know how to do this?

Kind regards, 


Gijs Korremans
RD Department

Global Supply Chain Services (pty) Ltd.
P.O. Box 1263
Rivonia 2128
South Africa
Tel: +27 (0)11 802 1329
Fax: +27 (0)11 802 6528
E-mail: [EMAIL PROTECTED]

--
This message has been scanned for viruses and
dangerous content by Network Sentry, and is
believed to be clean.
http://www.networksentry.co.za

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


Re: Lisp-likeness

2005-03-16 Thread Peter Lewerin
Fred Gilham [EMAIL PROTECTED] wrote 

  And Lisp's macro language isn't involved at all here.

 Also, #' is a read-macro.

A read-macro and a macro aren't the same thing.

 Then there's the defun macro . . . .

There is IMHO a difference between using a macro and using the macro language.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python becoming less Lisp-like

2005-03-16 Thread Torsten Bronger
Hallchen!

news.sydney.pipenetworks.com [EMAIL PROTECTED] writes:

 Torsten Bronger wrote:

 [...]

 I have exactly the same impression, but for me it's the reason
 why I feel uncomfortable with them.  For example, I fear that a
 skilled package writer could create a module with surprising
 behaviour by using the magic of these constructs.  I don't know
 Python well enough to get more specific, but flexibility almost
 always make confusing situations for non-hackers possible.

 In that case I wouldn't worry about the magic which can be done in
 python but the magic which can be done in C (which many modules
 are written in).

The magic in Python must allow the magic in C.

 Sometimes I think people complain just to complain.

It's interesting though that the concerns I mentioned have
influenced so many language designs, isn't it?

Look, you may weight the pros and cons differently from me, that's
perfectly okay.  But don't tell me my thoughts were invalid.

Tsch,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: About Databases...

2005-03-16 Thread Ola Natvig
Dennis Lee Bieber wrote:
Firebird -- developed from Interbase 6, released last summer.
	Maybe MaxDB by MySQL, developed from SAS DB (and likely
available with similar licenses as MySQL -- I don't know if MySQL AB
plan to merge SAS DB features into MySQL or the other way around G)
 

It was called SAP DB, I can recomend that one, the only trouble I've had 
with it is the Python drives in a heavily threaded environment, even 
with locking.

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


Re: iterable terminology (for language lawyers)

2005-03-16 Thread Raymond Hettinger
Michele Simionato]
 According to the standand library
 (http://docs.python.org/lib/typeiter.html)
 an *iterable* is something with an __iter__ method. This means that
 strings are *not* iterable.

The referenced section also says, Sequences, described below in more
detail, always support the iteration methods.  And since strings are
sequences, strings
*are* iterable.



 The reason why I ask for a clarification is that I am going to
 give a course at the ACCU conference, so I want to
 make sure I use the rigth terminology.

You're best bet is to quote the tutorial's glossary,
http://docs.python.org/tut/node18.html :

iterable
A container object capable of returning its members one at a time.
Examples of iterables include all sequence types (such as list, str,
and tuple) and some non-sequence types like dict and file and objects
of any classes you define with an __iter__() or __getitem__() method.
Iterables can be used in a for loop and in many other places where a
sequence is needed (zip(), map(), ...). When an iterable object is
passed as an argument to the builtin function iter(), it returns an
iterator for the object. This iterator is good for one pass over the
set of values. When using iterables, it is usually not necessary to
call iter() or deal with iterator objects yourself. The for statement
does that automatically for you, creating a temporary unnamed variable
to hold the iterator for the duration of the loop. See also iterator,
sequence, and generator.


Raymond Hettinger

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


Re: iterable terminology (for language lawyers)

2005-03-16 Thread Michele Simionato
R. Hettinger wrote:
 You're best bet is to quote the tutorial's glossary,
 http://docs.python.org/tut/node18.html :

Aha! That glossary looks like a nice new addition to the tutorial.
Maybe the standard library and the language
reference should link to it somewhere? (maybe
there already such links but I missed them).

Would you agree with Leif's definition that iterable is
any x such that iter(x) does not raise an error? On top
of my head I don't find any counter example and it
is the kind of definition I had in mind.

   Michele Simionato

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


Re: Lisp-likeness

2005-03-16 Thread Fernando
On Wed, 16 Mar 2005 00:36:40 +0100, Marcin 'Qrczak' Kowalczyk
[EMAIL PROTECTED] wrote:




BTW, the fact that a closure refers to a variable itself rather to its
current value can be used to check the true attitude of languages with
respect to functional programming, by observing how they understand
their basic loops :-)

Python loses:

 closures = []
 for i in range(10):
...def add(x):
...   return x + i
...closures.append(add)
...
 closures[5](1000)
1009

[snip]
Scheme wins:

 (let ((closures (make-vector 10)))
(do ((i 0 (+ i 1)))
((= i 10))
(vector-set! closures i (lambda (x) (+ x i
((vector-ref closures 5) 1000))
1005

and what is perhaps surprising, Perl wins:

$ perl -e '
   foreach my $i (0..9) {
  push @closures, sub {$_[0] + $i}
   }
   print $closures[5](1000), \n'
1005

Smalltalk 'loses' too:

closures := Array new: 10.
1 to: 10 do: [:i |
closures at: i put: [:x| x + i]].

(closures at: 5) value: 1000
returns 1011



If you think it's unlikely that one would want to keep a closure
referring to a loop control variable longer than the loop iteration
which has created it, think about the loop body spawning a thread.

I'm still not convinced this is really useful, but Scheme's behavior
seems more intuitive.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Good use for Jython

2005-03-16 Thread Michael Hoffman
Mike Wimpe wrote:
Other than being used to wrap Java classes, what other real use is
there for Jython being that Python has many other GUI toolkits
available? Also, these toolkits like Tkinter are so much better for
client usage (and faster) than Swing, so what would be the advantage
for using Jython?
What ever gave you the impression that Jython was targeted only at
people who wanted to do GUI development?
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing the contents of a 'cell' object from Python

2005-03-16 Thread Duncan Booth
Jeff Epler wrote:

 Here's an old thread I contributed to which had a similar function
 (called 'cell_get' in this case)
 
 http://groups-beta.google.com/group/comp.lang.python/browse_thread/thre
 ad/baba3b943524a92c/71b57a32b311ffc8?q=func_closure#71b57a32b311ffc8 
 http://groups-beta.google.com/group/comp.lang.python/msg/71b57a32b311ff
 c8?dmode=source 
 

And if you want to set the value of a cell variable you can perform 
similar tricks see:

http://groups.google.co.uk/groups?selm=Xns95F991C538FC3duncanrcpcouk%40127.0.0.1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode study with unicodedata module

2005-03-16 Thread Xah Lee
here's a snippet of code that prints a range of unicode chars, along
with their ordinal in hex, and name.

chars without a name are skipped. (some of such are undefined code
points.)

On Microsoft Windows the encoding might need to be changed to utf-16.

Change the range to see different unicode chars.

# -*- coding: utf-8 -*-

from unicodedata import *

l=[]
for i in range(0x, 0x0fff):
l.append(eval('u\\u%04x' % i))

for x in l:
if name(x,'-')!='-':
print x.encode('utf-8'),'|', %04x%(ord(x)), '|', name(x,'-')
--
http://xahlee.org/perl-python/unicodedata_module.html

anyone wants to supply a Perl version?

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html



Brian McCauley wrote:
 Xah Lee wrote:

  i don't know what's the state of Perl's unicode.
 
 perldoc perlunicode

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


Re: [perl-python] unicode study with unicodedata module

2005-03-16 Thread Xah Lee
Fuck google incorporated for editing my subject name without
permission.

and fuck google incorporated  for editing my message content without
permission.

http://xahlee.org/UnixResource_dir/writ/responsible_license.html

 Xah
 [EMAIL PROTECTED]
 http://xahlee.org/PageTwo_dir/more.html

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


multiple import of a load of variables

2005-03-16 Thread Torsten Bronger
Hallchen!

I have a file that looks a little bit like a C header file with a
long list of variables (actually constants) definitions, e.g.

VI_ATTR_TIMO = 0x54378
...

Actually I need this in a couple of low-level modules that are
imported into the main module, and in the main module itself.  They
may be also used in the programs that import the main module.

Probably it doesn't mean a significant loss of performance anyway
since all of it is done only at startup, but I wonder whether it's
better to keep everything that depends on this header file
together so that it must be looked over by Python only once.  Is
this correct, or is there some sort of implicit optimisation that
makes both variants almost equivalent?

Tsch,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiple import of a load of variables

2005-03-16 Thread Fuzzyman

Torsten Bronger wrote:
 Hallöchen!

 I have a file that looks a little bit like a C header file with a
 long list of variables (actually constants) definitions, e.g.

 VI_ATTR_TIMO = 0x54378
 ...

 Actually I need this in a couple of low-level modules that are
 imported into the main module, and in the main module itself.  They
 may be also used in the programs that import the main module.

 Probably it doesn't mean a significant loss of performance anyway
 since all of it is done only at startup, but I wonder whether it's
 better to keep everything that depends on this header file
 together so that it must be looked over by Python only once.  Is
 this correct, or is there some sort of implicit optimisation that
 makes both variants almost equivalent?


I'm not entirely clear what you are trying to do *but* - if you import
the same module in several places (per interpreter instance of course)
the import will only be done *once*. The other import statments just
make that namespace available from the namespace that does the import.

This means there is little extra overhead for importing a module that
has already been imported elsewhere.

HTH ?

Regards,

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


 Tschö,
 Torsten.
 
 -- 
 Torsten Bronger, aquisgrana, europa vetus

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


Re: Turning String into Numerical Equation

2005-03-16 Thread Giovanni Bajo
Steven Bethard wrote:

 When __builtin__ is not the standard __builtin__, Python is in
 restricted execution mode.

 Do you know where this is documented?  I looked around, but couldn't
 find anything.


I found some documentation in the reference of the (now disabled) modules for
Restricted Execution (chapter 17 in the Library Reference). Quoting:


The Python run-time determines whether a particular code block is executing in
restricted execution mode based on the identity of the __builtins__ object in
its global variables: if this is (the dictionary of) the standard __builtin__
module, the code is deemed to be unrestricted, else it is deemed to be
restricted.


There are also some hints in the documentation for eval() itself:


If the globals dictionary is present and lacks '__builtins__', the current
globals are copied into globals before expression is parsed. This means that
expression normally has full access to the standard __builtin__ module and
restricted environments are propagated


In fact, the documentation for eval() could be improved to explain the benefits
of setting __builtins__ in the globals.
-- 
Giovanni Bajo


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


Re: Lisp-likeness

2005-03-16 Thread Michele Simionato
Or, just to impress Lispers,

 def add(x,y):
... return x + y
 closures = []
 for i in range(10):
...closures.append(add.__get__(i))
...
 closures[5](1000)
1005

Remember, in Python do not have functions, we have descriptors! ;)

Michele Simionato

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


Re: code for Computer Language Shootout

2005-03-16 Thread Raymond Hettinger
Consider keeping the alias for append because it occurs in the
innermost loop.   For maximum readability, write:  addline = seq.append

Move the ''.join() to the show() function.  That eliminates a little
redundancy.

The test dataset doesn't use the semi-colon comment field.  So,
consider reversing ';' to ';'.


Raymond Hettinger

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


Re: unicode converting

2005-03-16 Thread Serge Orlov
Maxim Kasimov wrote:
 Christos TZOTZIOY Georgiou wrote:
 
  If unicode_data references your unicode data, all you have to send
is:
 
  unicode_data.encode('utf-16') # maybe utf-16be for network order
 
 is utf-16 string the same ucs-2? my question is how to get string
 encoded as UCS-2

utf-16 is basically a superset of ucs-2. See here for more detail:
http://www.azillionmonkeys.com/qed/unicode.html
If you ensure that ord() of each output character is  0x1
you'll get valid ucs-2 output if you use utf-16 encoding. If you
build python with --enable-unicode=ucs2 no character can be = 0x1
so you don't have to check. On the other 1) you won't be able even to
input characters = 0x1 into your application and 2) premature
optimization is bad and 3) There is a note in README: To compile
Python2.3 with Tkinter, you will need to pass --enable-unicode=ucs4
flag to ./configure

  Serge.

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


Re: getting data with proper encoding to the finish

2005-03-16 Thread Ksenia Marasanova
John, Serge, thanks for your help!

utf-16le  encoding didn't help. I had however to solve it yesterday,
so I used csv module to create CSV file and then import it in Excel.
Excel still had troubles with accented characters, but this is another
story: it seems that Office 2004 Excel (for Mac, but I assume the PC
version is no better) cannot import UTF-8 encoded text files. Encoding
CSV file with Latin1 encoding finally did work.

Now back to the Excel story, I also think that there is something
wrong with pyExcelWriter or the way I use it. CSV file generation was
okay, so I think there is nothing wrong with my data,  or XML parser.

I will resume in a few days with pyExcelWriter and will post the
results here, but anyway, many thanks for your time and explanation!


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


Re: Python becoming less Lisp-like

2005-03-16 Thread news.sydney.pipenetworks.com
Torsten Bronger wrote:
Hallchen!
news.sydney.pipenetworks.com [EMAIL PROTECTED] writes:

Torsten Bronger wrote:

[...]
I have exactly the same impression, but for me it's the reason
why I feel uncomfortable with them.  For example, I fear that a
skilled package writer could create a module with surprising
behaviour by using the magic of these constructs.  I don't know
Python well enough to get more specific, but flexibility almost
always make confusing situations for non-hackers possible.
In that case I wouldn't worry about the magic which can be done in
python but the magic which can be done in C (which many modules
are written in).

The magic in Python must allow the magic in C.
You have answered your own question.
Sometimes I think people complain just to complain.

It's interesting though that the concerns I mentioned have
influenced so many language designs, isn't it?
Look, you may weight the pros and cons differently from me, that's
perfectly okay.  But don't tell me my thoughts were invalid.
I agree. It was an uncalled for statement and I apologise. I guess 
theres got to be critics for the language to become better.

I just think certain arguments are a bit thin. Especially all the talk 
about the decorator syntax. I have never seen so much discussion over 
such a small detail. It's not as if the BDFL is going to start 
introducing all types of special chars in the language. From the way 
people carry on, it shall as heck sounds like it.

More in relation to the original topic, why can't people just ignore 
features they don't understand and may never use directly. Tell me you 
understand exactly how every single module you have ever used works 
whether or not its written in pure simple python or python with hacky 
features. Regardless of how a piece of software is written, as long as 
it works, has a good test bed, has a smart programmer behind, then lets 
trust the guy to do a good job. If you don't, then you can write it 
yourself which means you can do exactly how you want it which again 
makes the whole argument mute.

You can't take a ride on someones sweat and blood and expect them to 
control how they program as well can you ? If you're paying them, then 
make sure they don't use any special features.

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


Mod_python installation: apache Warning

2005-03-16 Thread Andrea Fiore
Hello,
i have compiled mod_python 2.7.10 on a Linux box with Apache 1.3.31,
but after i restarted the web server, i had a strange warning that i
did non understand

**
bash-2.05b# apachectl configtest
[Wed Mar 16 11:50:26 2005] [warn] Loaded DSO
/usr/libexec/apache/mod_python.so uses plain Apache 1.3 API, this
module might crash under EAPI! (please recompile it with -DEAPI)
Syntax OK
**

What is EAPI? what is DEAPI?
How can i recompile it with DEAPI? (./configure -with-DEAPI doesn't
work! ;-)


Thank you in advance,
Andrea
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiple import of a load of variables

2005-03-16 Thread Torsten Bronger
Hallchen!

Fuzzyman [EMAIL PROTECTED] writes:

 [...]

 I'm not entirely clear what you are trying to do

The following: variables.py looks like this

a = 1
b = 2

Then I have helper_a.py, helper_b.py, and helper_c.py which begin
with

from variables import *

And finally, my_module.py starts with

from variables import *
from helper_a.py import *
from helper_c.py import *
from helper_c.py import *

Now imagine that variables.py contained not only two but hundreds of
variables.  Is this then still the most effective approach?

 *but* - if you import the same module in several places (per
 interpreter instance of course) the import will only be done
 *once*. The other import statments just make that namespace
 available from the namespace that does the import.

Even if I use from?

Tsch,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiple import of a load of variables

2005-03-16 Thread Fuzzyman

Torsten Bronger wrote:
 Hallöchen!

 Fuzzyman [EMAIL PROTECTED] writes:

  [...]
 
  I'm not entirely clear what you are trying to do

 The following: variables.py looks like this

 a = 1
 b = 2

 Then I have helper_a.py, helper_b.py, and helper_c.py which begin
 with

 from variables import *

 And finally, my_module.py starts with

 from variables import *
 from helper_a.py import *
 from helper_c.py import *
 from helper_c.py import *

 Now imagine that variables.py contained not only two but hundreds of
 variables.  Is this then still the most effective approach?


Hello Torsten,

This looks like the most effective approach to me. The additional cost
of the extra import statements would be very low. The alternative would
be to parse a config file and pass a data structure (containing all the
variables) between your modules. I can't imagine there is less overhead
in this. Either that or refactor so you only use the variables in one
place.

  *but* - if you import the same module in several places (per
  interpreter instance of course) the import will only be done
  *once*. The other import statments just make that namespace
  available from the namespace that does the import.

 Even if I use from?


Yes - all you do with the 'from' approach is get a direct reference to
that value, it still exists in it's original namespace.

import module
value = module.value
and :
from module import value

are exactly equivalent. The only difference is that the first construct
makes the whole of the 'module' namespace available as well - it no
less exists with the second construct though... you're just not keeping
a reference to it directly.

Not using the 'from' construct requires a bit of extra typing - but is
more explicit as to where the variables are coming from. This might
make your code a bit more readable.

Regards,

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

 Tschö,
 Torsten.
 
 -- 
 Torsten Bronger, aquisgrana, europa vetus

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


Re: [Pmw] reusing a graph after deleting a curve

2005-03-16 Thread giacomo boffi
giacomo boffi [EMAIL PROTECTED] writes:

 my question: is it possible to erase a graph, and reuse it?

 like in

 # x - compute - y
 g=Pmw.Blt.Graph(); g.pack()
 g.line_create(name,x,y)
 # other computing - a better y
 # do something to g, erasing the previous plot
 #[the above is the part that i cannot understand...]
 g.line_create(name,x,y)


ok, i've got it:

  g.element_configure(name,ydata=a_better_y)

if a Pmw.Blt hacker is listening, i cannot understand why on earth
it's named element_configure, and not line_configure (yes, lines and
bars are both elements, but...)

-- 
vabbuò parliamo d'altro-- Agnosco, in IFQ
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting data with proper encoding to the finish

2005-03-16 Thread Serge Orlov

Ksenia Marasanova wrote:
 John, Serge, thanks for your help!

 utf-16le  encoding didn't help. I had however to solve it yesterday,
 so I used csv module to create CSV file and then import it in Excel.
 Excel still had troubles with accented characters, but this is
another
 story: it seems that Office 2004 Excel (for Mac, but I assume the PC
 version is no better) cannot import UTF-8 encoded text files.

Right, I tried on windows xp, utf-8 csv file is imported as garbadge.
However, csv file saved in utf-16 encoding is imported correctly.

 Encoding
 CSV file with Latin1 encoding finally did work.

 Now back to the Excel story, I also think that there is something
 wrong with pyExcelWriter or the way I use it. CSV file generation was
 okay, so I think there is nothing wrong with my data,  or XML parser.

 I will resume in a few days with pyExcelWriter and will post the
 results here, but anyway, many thanks for your time and explanation!

I believe Microsoft Office has gone through byte strings to unicode
strings transformation between 1995 and 1997. I still remember times
when you could receive Microsoft Office file and couldn't view it.
I suspect pyExcelWriter writes strings in that old format so utf-16le
trick didn't work. You can try to contact pyExcelWriter author
and ask him about unicode support.

  Serge.

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


Re: compiled open source Windows lisp (was Re: Python becoming less Lisp-like)

2005-03-16 Thread Carl Shapiro
Brandon J. Van Every [EMAIL PROTECTED] writes:

 Last I looked, 2 years ago?, there were no compiled, open source lisps that
 ran on Windows.  Has this changed?

I have a virtually completed port of CMUCL to Win32.  And, if I was
not busy organizing a Lisp conference, it would be publicly available
by now.  An observation: most of the open-source Lisp implementations
make egregious assumptions about the underlying operating system, most
of which are just barely valid, even on UNIX.  (Perhaps this is an
observation about UNIX software in general.)  A lot of this had to be
untangled in order to make CMUCL usable.  More work remains to be
done.

When playing the role of a Windows developer, I have never been
satisfied with the level of integration that language run-times with a
UNIX heritage has to the Win32 API.  Such things as file system
interaction, I/O completion ports, thread pools, componentized
software, synchronization primitives and the like never quite work
correctly, especially when there is a run-time library which sits
above the C library.  You will find an amazing amount of shennanigans
in Lisp run-time libraries (commercial and open-source) as well as
those belonging to the various strongly-typed functional languages,
and scripting languages.  These systems would appear to have been
written with the assumption that they would be the harness of an
application, and that UNIX compatibility was an overriding concern;
fatal flaws for Win32 development.

I have never been a game developer, but I have worked on real-time
systems--written in Lisp.  I would guess that programmers in both
these domains have similar concerns.  You can write continuous systems
in Lisp, but it requires a fair amount of wizardry.  (This is
basically true of most garbage collected systems.)  Real-time
collectors help but often sap performance and introduce constraints of
their own.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Turning String into Numerical Equation

2005-03-16 Thread Giovanni Bajo
Michael Spencer wrote:

 In fact, I believe my solution to be totally safe,

 That's a bold claim!  I'll readily concede that I can't access
 func_globals from restricted mode eval (others may know better).  But
 your interpreter is still be vulnerable to DOS-style attack from
 rogue calculations or quasi-infinite loops.


Yes, but I don't see your manually-rolled-up expression calculator being
DOS-safe. I believe DOS attacks to be a problem whenever you want to calculate
the result of an expression taken from the outside. What I was trying to show
is that my simple one-liner is no worse than a multi-page full-blown expression
parser and interpreter.
-- 
Giovanni Bajo


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


Re: unicode converting

2005-03-16 Thread TZOTZIOY
On 16 Mar 2005 02:53:12 -0800, rumours say that Serge Orlov
[EMAIL PROTECTED] might have written:

3) There is a note in README: To compile
Python2.3 with Tkinter, you will need to pass --enable-unicode=ucs4
flag to ./configure

I thought this applied to Tkinter as pre-built on recent RedHat systems.  Does
it also apply to FreeBSD?  On Windoze, Mandrake and SuSE python has UCS-2
unicode and Tkinter is working just fine.
-- 
TZOTZIOY, I speak England very best.
Be strict when sending and tolerant when receiving. (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RotatingFileHandler and logging config file

2005-03-16 Thread news.sydney.pipenetworks.com
Rob Cranfill wrote:
Kent Johnson wrote:
It is in the latest docs.
Kent

No, it isn't. (But thanks for replying anyway!)
  http://docs.python.org/lib/logging-config-fileformat.html

You're looking in the wrong place. Try
http://docs.python.org/lib/node333.html

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


Re: About Databases...

2005-03-16 Thread Leif B. Kristensen
Peter A. Schott wrote:

 PostGreSQL - good feature set, open source.  Not sure on speed, but it
 should run natively on Unix, Linux, and Win32 (not sure about BSD or
 others).

A lot of the core developers of PostgreSQL are apparently running *BSD.
On the PostgreSQL-General mailing list, I've noted that people run it
on Solaris, AIX, HP-UX and all kinds of 'nixes. I think that the
keyword is POSIX compliance.

The native Win32 version (8.x) is very recent, and probably not a good
bet for a production environment for the time being. Earlier versions
may be run under Cygwin.

The speed of a database engine is notoriously hard to assess by
objective means. It will depend on tuning, indexing, load, read/write
ratio, number of concurrent users, and a lot of other variables. Some
RDBMSs also performs terribly in situations where others shine.

Anyway, I'd recommend a closer study of PostgreSQL for anyone interested
in a good RDBMS. I have been using MySQL for several years, but have
recently come to appreciate all the advanced features of PostgreSQL
that still is kind of vaporware in MySQL.
-- 
Leif Biberg Kristensen
just another global village idiot
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lisp-likeness

2005-03-16 Thread Michele Simionato
Carl Banks:
 Python might lose when it comes to functional programming,
 but it wins when it comes to nested functions like this (where
a,b,c,d
 are in the enclosing scope and presumably changing):

   def print_variables():
print a,b,c,d

Yes, clearly if I have

def toplevel():
a = 1
def f():
print a
a = 2
f()

toplevel()

I want 2 to be printed, not 1.

 If Python did it the way Scheme did, this would be pretty useless.

But notice that Scheme has no problems whatsoever:

(define (toplevel)
  (define a 1)
  (define (f)
(display a))
  (set! a 2)
  (f))

(toplevel)

prints 2 the same as in Python.

 IMO, this sort of usage is FAR more common than the functional usage
as
 a closure inside a loop.

Maybe, but for me it is quite common to have closures inside loops
(typically for callbacks in Tkinter or a Web framework).

 Closing on a value rather than a variable would have been a lot
easier
 to implement.  I'm sure there was talk about which way to do it in
the
 discussions about adding nested scopes to the language, and if the
 Python gods felt closing on a variable wasn't significantly more
useful
 than closing on a value, I doubt they would have done that.

I have no doubt about that. Still, there are people who disagrees
with Guido's choice, even on python-dev. This was a tough decision
to make, with pros and contras. It would be possible to change
the current default and have a more Schemish/Haskellish syntax
for loops: it would be enough to internally convert something like

result = []
for i in range(10):
result.append(lambda : i)

into

result = []
def for_block(i):
result.append(lambda : i)
for i in range(10): for_block(i)

However this approach has a drawback (which is not there in Scheme,
since Scheme has set!): if a new scope was created at each iteration
(which is what the function call is doing) we could not reassign
variables (i.e. they would become names locals to the for scope,
touching them would not affect variables outside the scope).
So this idiom

a = 
for i in range(10):
  if i == 5: a = 5 was reached
print a

would not work. So, as I said, there are pros and contros.
Personally, I like better the Scheme way (what I do not like
in Scheme is the issue of inner defines vs. toplevel defines,
but this is another story).

   Michele Simionato

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


Re: About Databases...

2005-03-16 Thread PA
On Mar 16, 2005, at 12:59, Leif B. Kristensen wrote:
Anyway, I'd recommend a closer study of PostgreSQL for anyone 
interested
in a good RDBMS.
Talking of which, I would recommend to take a serious look at FrontBase:
http://www.frontbase.com/
Excellent database, running on pretty much anything. While not open 
source, they do offer a free, unlimited license (E-Starter).

Cheers
--
PA, Onnay Equitursay
http://alt.textdrive.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Listbox fill=BOTH expand=YES (Tkinter)

2005-03-16 Thread TZOTZIOY
On Tue, 15 Mar 2005 16:48:17 +0300, rumours say that Raseliarison nirinA
[EMAIL PROTECTED] might have written:

yes, indeed. 
 import Tkconstants
 'True' and 'YES' in dir(Tkconstants)
True

thanks Harlin,

I hope you also know that

. 'inexistent keyword' and 'YES' in dir(Tkconstants)

is also True...
-- 
TZOTZIOY, I speak England very best.
Be strict when sending and tolerant when receiving. (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode converting

2005-03-16 Thread Serge Orlov
Christos TZOTZIOY Georgiou wrote:
 On 16 Mar 2005 02:53:12 -0800, rumours say that Serge Orlov
 [EMAIL PROTECTED] might have written:

 3) There is a note in README: To compile
 Python2.3 with Tkinter, you will need to pass --enable-unicode=ucs4
 flag to ./configure

 I thought this applied to Tkinter as pre-built on recent RedHat
 systems. Does it also apply to FreeBSD?

I don't know. I didn't notice that it was about RedHat.

 On Windoze, Mandrake and SuSE python has UCS-2
 unicode and Tkinter is working just fine.

Did you build python on Mandrake and SuSE yourself? I had an impression
that ucs-4 builds are prefered on Linux. At least python on RedHat EL3
and SUSE ES9 is built with --enable-unicode=ucs4.

  Serge.

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


Re: Lisp-likeness

2005-03-16 Thread Pascal Bourguignon
[EMAIL PROTECTED] (Peter Lewerin) writes:

 Fred Gilham [EMAIL PROTECTED] wrote 
 
   And Lisp's macro language isn't involved at all here.
 
  Also, #' is a read-macro.
 
 A read-macro and a macro aren't the same thing.
 
  Then there's the defun macro . . . .
 
 There is IMHO a difference between using a macro and using the
 macro language.

What macro language?  Common-Lisp?

-- 
__Pascal Bourguignon__ http://www.informatimago.com/
I need a new toy.
Tail of black dog keeps good time.
Pounce! Good dog! Good dog!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lisp-likeness

2005-03-16 Thread Marcin 'Qrczak' Kowalczyk
Carl Banks [EMAIL PROTECTED] writes:

 BTW, the fact that a closure refers to a variable itself rather to
 its current value can be used to check the true attitude of
 languages with respect to functional programming, by observing how
 they understand their basic loops :-)

 Closing on a value rather than a variable would have been a lot easier
 to implement.

To be clear: closing on the variable is the only sane choice. Closing
on its current value would be inconsistent with global variables and
no language does this.

The issue is about the semantics of loops: whether they introduce
a new variable for each iteration, or change the value of a single
variable.

-- 
   __( Marcin Kowalczyk
   \__/   [EMAIL PROTECTED]
^^ http://qrnik.knm.org.pl/~qrczak/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode converting

2005-03-16 Thread TZOTZIOY
On 16 Mar 2005 04:21:16 -0800, rumours say that Serge Orlov
[EMAIL PROTECTED] might have written:

 On Windoze, Mandrake and SuSE python has UCS-2
 unicode and Tkinter is working just fine.

Did you build python on Mandrake and SuSE yourself? I had an impression
that ucs-4 builds are prefered on Linux. At least python on RedHat EL3
and SUSE ES9 is built with --enable-unicode=ucs4.

[EMAIL PROTECTED]/home/tzot/tmp
$ py
Python 2.4 (#8, Mar  2 2005, 11:12:44)
[GCC 3.3.3 (SuSE Linux)] on linux2
Type help, copyright, credits or license for more information.
. import sys
. sys.maxunicode
65535
. import Tkinter
.
You have new mail in /var/mail/tzot
[EMAIL PROTECTED]/home/tzot/tmp
$ python
Python 2.3.3 (#1, Aug 31 2004, 13:51:39)
[GCC 3.3.3 (SuSE Linux)] on linux2
Type help, copyright, credits or license for more information.
. import sys, Tkinter
. sys.maxunicode
1114111
.

2.4 built by me, 2.3.3 by SuSE.

I see.  So on SuSE 9.1 professional too, Python and Tcl/Tk are pre-built with
ucs-4.  My Mandrake installation is at home and I can't check now.  Sorry for
the misinformation about SuSE.
-- 
TZOTZIOY, I speak England very best.
Be strict when sending and tolerant when receiving. (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Lisp-likeness

2005-03-16 Thread Carl Banks

Michele Simionato wrote:
 Carl Banks:
  If Python did it the way Scheme did, this would be pretty useless.

 But notice that Scheme has no problems whatsoever:

 (define (toplevel)
   (define a 1)
   (define (f)
 (display a))
   (set! a 2)
   (f))

 (toplevel)

 prints 2 the same as in Python.

Hmm. On closer inspection, I'm going to have to amend my implictation
of Scheme: the example poster was cheating.  Scheme and Python both do
closures the same way.  However, the Scheme snippet in the original
example used a let-block.  I.e., it introduced a new scope, whereas the
Python example did not (because it doesn't have anything like let).


-- 
CARL BANKS

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


Re: Why tuple with one item is no tuple

2005-03-16 Thread Antoon Pardon
Op 2005-03-16, Tim Roberts schreef [EMAIL PROTECTED]:
 Gregor Horvath [EMAIL PROTECTED] wrote:

 type(['1'])
type 'list'

 type(('1'))
type 'str'

I wonder why ('1') is no tuple

 There were lots of answers, but I'm not sure I saw the why addressed.

 Consider this:

 a = (3 + 5) * 5

 You really, really want (3 + 5) to be an integer, not a one-item tuple.

I sometimes do wonder if some impliciteness wouldn't be better here,
so that any item could be treated as if it was a one-item tuple.

A bit like every char being a string.

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


Re: Why tuple with one item is no tuple

2005-03-16 Thread Diez B. Roggisch
 Consider this:
 a = (3 + 5) * 5
 You really, really want (3 + 5) to be an integer, not a one-item tuple. 
 
 I sometimes do wonder if some impliciteness wouldn't be better here,
 so that any item could be treated as if it was a one-item tuple.
 
 A bit like every char being a string.

There is no char. There are strings of lenght 1. And the above example makes
it clear that there would be an ambiguity that could _maybe_ be solved in a
static typed language (the application of the (3+5) as left side to the
operator * if * only is defined as [num, num] - num), but clearly not
in a dynamic typed one as python.

And if the static typed language allows operator overloading, it could very
well be that someone creates a overloading for 

* : [tuple[num], tuple[num]] - whatever

which would reintroduce the ambiguity.

Soo, in the end it boils down to some explicitness - where IMHO an
additional comma is pretty much no problem at all. Another option would of
course be the introduction of different parentheses for tuples - but I
can't find some on my keyboard.

-- 
Regards,

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


Re: ElementTree/DTD question

2005-03-16 Thread Fredrik Lundh
Greg Wilson wrote:

 My first attempt was this XML file:

 --

 ?xml version=1.0 encoding=UTF-8?
 !DOCTYPE lec [
  !ENTITY ldots #x8230;
 ]
 lec title=Introduction
 topic title=Motivation summary=motivation for course
 slide
  b1Write an introductionldots;/b1
 /slide
 /topic
 /lec

 --

 Running python validate.py first.xml produces:

 --

 Traceback (most recent call last):
  File validate.py, line 7, in ?
ElementTree.parse(filename)
  File C:\Python23\Lib\site-packages\elementtree\ElementTree.py,
 line 865, in parse
tree.parse(source, parser)
  File C:\Python23\Lib\site-packages\elementtree\ElementTree.py,
 line 589, in parse
parser.feed(data)
  File C:\Python23\Lib\site-packages\elementtree\ElementTree.py,
 line 1160, in feed
self._parser.Parse(data, 0)
  File C:\Python23\Lib\site-packages\elementtree\ElementTree.py,
 line 1113, in _default
raise expat.error(
 xml.parsers.expat.ExpatError: undefined entity ldots;: line 9, column
 27

 --

looks like a bug in the Python version of elementtree.  you can either switch
to cElementTree, or apply the following patch:

Index: elementtree/ElementTree.py
===
--- elementtree/ElementTree.py  (revision 2315)
+++ elementtree/ElementTree.py  (working copy)
@@ -1120,7 +1120,7 @@
 self._target = target
 self._names = {} # name memo cache
 # callbacks
-parser.DefaultHandler = self._default
+parser.DefaultHandlerExpand = self._default
 parser.StartElementHandler = self._start
 parser.EndElementHandler = self._end
 parser.CharacterDataHandler = self._data

(for quicker responses to elementtree questions, use the xml-sig mailing list)

/F 



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


Re: Lisp-likeness

2005-03-16 Thread Jacek Generowicz
Carl Banks [EMAIL PROTECTED] writes:

 Michele Simionato wrote:
  Carl Banks:
   If Python did it the way Scheme did, this would be pretty useless.
 
  But notice that Scheme has no problems whatsoever:
 
  (define (toplevel)
(define a 1)
(define (f)
  (display a))
(set! a 2)
(f))
 
  (toplevel)
 
  prints 2 the same as in Python.
 
 Hmm. On closer inspection, I'm going to have to amend my implictation
 of Scheme: the example poster was cheating.  Scheme and Python both do
 closures the same way.  However, the Scheme snippet in the original
 example used a let-block.  I.e., it introduced a new scope, whereas the
 Python example did not (because it doesn't have anything like let).

Yes, we've been over this many times. I'm surprised that Michele
hasn't yet referenced the thread where we exposed the gory details, as
was his custom for a while :-)



Message-ID: [EMAIL PROTECTED], for this particular
aspect, in case anyone gives a monkey's left testicle.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Downloading all files older than 3 hours from a ftp-server.

2005-03-16 Thread Fredrik Lundh
Christos TZOTZIOY Georgiou wrote:

 ISTR seeing a parsedate (or similar) for ftp sites by the effbot, but I am not
 sure.

you can get bindings for

http://cr.yp.to/ftpparse.html

from

http://c0re.23.nu/c0de/ftpparsemodule/

or

http://effbot.org/downloads/#ftpparse

/F 



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


Re: why this error?

2005-03-16 Thread Fredrik Lundh
spencer [EMAIL PROTECTED] wrote:

 I'm not sure why I can't concatenate dirname() with basename().

 Traceback (most recent call last):
  File showDir.py, line 50, in ?
print 'somthing new...', os.path.join(os.path.dirname(os.getcwd)) +
 os.path.basename(os.getcwd())
  File /usr/lib/python2.3/posixpath.py, line 119, in dirname
return split(p)[0]
  File /usr/lib/python2.3/posixpath.py, line 77, in split
i = p.rfind('/') + 1
 AttributeError: 'builtin_function_or_method' object has no attribute
 'rfind'

you're passing a function (os.getcwd) to dirname, not a directory name.

 os.getcwd
built-in function getcwd
 os.getcwd()
'/home/fredrik'

if you fix that, you get

 os.path.join(os.path.dirname(os.getcwd())) + ...

which is the same as

os.path.dirname(os.getcwd()) + ...

maybe you meant

 os.path.join(os.path.dirname(os.getcwd()), os.path.basename(os.getcwd()))

?

that's a rather odd way to write:

os.getcwd()

/F 



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


Getting current variable name

2005-03-16 Thread pl
Hi all,
I followed the mails entitled 'How to turn a variable name into a
string?' in march 2005 posts as I have a similar problem.

I have to get some list variable names at some point in my program. So
I ended up looking into globals() to get them with a small function like
this:

#!/usr/bin/python

l1 = ['r', 'r', 't']
l2 = ['r', 't', 't']
l3 = ['t', 't', 't']# Two equivalent lists but...
l4 = ['t', 't', 't']# with different names

def nameofObj(obj):
#   print locals()
globdict = globals()
var = globals().keys()
for i in var :
if globdict[i] == obj:
print i


print '-'*20 ,'\n'
nameofObj(l1)

print '-'*20 ,'\n'
map(nameofObj, [l1, l2, l3, l4])


If you try this, with 2 equivalent lists
(here l3 and l4 when using map) the function will return both
possibilities l3 and l4 which I understand. 
So this solution is limitated to unique lists, unfortunately I do have
equivalent lists in my case...

The problem comes from the fact that locals() and globals() have
in common their values but not the keys which then can't be tested.

The only solution I see would be to link the list and its name (in
a dictionary for instance) but that does not sound elegant to me?
If you guys can help a newbie...

Thank you
-- 
--
| Patrick LADAM   |   |
| Laboratoire CSSB| THE BIG BANG THEORY:  |
| UFR SMBH|   |
| 74 rue Marcel Cachin|   In the begining there was   |
| 93017 Bobigny CEDEX |nothing at all.|
|  NEW e-mail:  |   |
| [EMAIL PROTECTED] |  Then, it exploded... |
| Tel: 01 48 38 77 26 / 76 85 |   |
| Fax: 01 48 38 77 77 |   |
--




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


pyXPCOM with mozilla 1.7 + python 2.4

2005-03-16 Thread Ola Natvig
Hi all
Lately I've been trying to compile pyXPCOM on my windows machine. But 
I've successfully compiled mozilla without pyXPCOM but when I adds the 
pyXPCOM module the build fails with this message:

Error message:
d:/test\moz\mozilla\extensions\python\xpcom\src\VariantUtils.cpp(1151) :
error C2668: 'nsString::nsString' : ambiguous call to overloaded function
d:\test\moz\mozilla\obj-i586-pc-msvc\dist\include\string\nsTString.h(467
): could be 'nsString::nsString(PRUint32)'
d:\test\moz\mozilla\obj-i586-pc-msvc\dist\include\string\nsTString.h(73)
: or   'nsString::nsString(const nsAString::char_type
*,nsAString::size_type
)'
d:\test\moz\mozilla\obj-i586-pc-msvc\dist\include\string\nsTString.h(66)
: or   'nsString::nsString(nsAString::char_type)'
while trying to match the argument list '(int)'
I wonder if anyone hav expirienced this problem and perhaps found a 
solution to it.

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


Re: Lisp-likeness

2005-03-16 Thread Michele Simionato
 I'm surprised that Michele
hasn't yet referenced the thread where we exposed the gory details, as
was his custom for a while :-)
Message-ID: [EMAIL PROTECTED], for this particular
aspect, in case anyone gives a monkey's left testicle.

I had forgot the title of that thread and also I wanted
to spare the poor monkeys :)

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


Re: Why tuple with one item is no tuple

2005-03-16 Thread Antoon Pardon
Op 2005-03-16, Diez B. Roggisch schreef [EMAIL PROTECTED]:
 Consider this:
 a = (3 + 5) * 5
 You really, really want (3 + 5) to be an integer, not a one-item tuple. 
 
 I sometimes do wonder if some impliciteness wouldn't be better here,
 so that any item could be treated as if it was a one-item tuple.
 
 A bit like every char being a string.

 There is no char. There are strings of lenght 1.

That is a matter of view. But to illustrate what I mean,
the following is an infinite loop in python

  s = 'hi'
  while true:
s = s[0]

 And the above example makes
 it clear that there would be an ambiguity that could _maybe_ be solved in a
 static typed language (the application of the (3+5) as left side to the
 operator * if * only is defined as [num, num] - num), but clearly not
 in a dynamic typed one as python.

That ambiguity is only caused because python uses the same characters
for very different operations and to be honest I don't like that.

for instance I have written once somekind of vector class where
it was natural for these vectors to be added as well as te be
concatenated. Unfortunately python uses + for both so I had
no way to have both operators in a natural way in python.

So that a * would create an ambiguity if items would be silently
transformed in a one-item tuple when appropiate is IMO more caused
by the design decision to use * for two totally diffent operations
then because of the dynamic nature of python.

 And if the static typed language allows operator overloading, it could very
 well be that someone creates a overloading for 

* : [tuple[num], tuple[num]] - whatever

 which would reintroduce the ambiguity.

 Soo, in the end it boils down to some explicitness - where IMHO an
 additional comma is pretty much no problem at all. Another option would of
 course be the introduction of different parentheses for tuples - but I
 can't find some on my keyboard.

Well I can't find braille on my keyboard, but if I wanted to, it
wouldn't be difficult to get it on my screen. So is it with
different parentheses. That python can't use these parentheses
is again a design decision.

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


computing a weighted sum

2005-03-16 Thread andreif
Suppose I have a list of n floats x and a list of n floats w and I want
to compute x[0]*w[0] + .. + x[n-1]*w[n-1].

Is there some elegant expression (perhaps using lambda) to have it done
in one statement ? As in :
 y = lambda x,w : ...

I ask because the way I am doing it now :
  y = 0
  for i in range(0,n): y += x[i]*w[i]

doesn't seem very pythonic :)

Thanks,
Andrei

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


Re: computing a weighted sum

2005-03-16 Thread Will McGugan
[EMAIL PROTECTED] wrote:
Suppose I have a list of n floats x and a list of n floats w and I want
to compute x[0]*w[0] + .. + x[n-1]*w[n-1].
Is there some elegant expression (perhaps using lambda) to have it done
in one statement ? As in :
 y = lambda x,w : ...
I ask because the way I am doing it now :
  y = 0
  for i in range(0,n): y += x[i]*w[i]
doesn't seem very pythonic :)
I'll take a stab at that!
In Python 2.3
sum( [ _x * _w for _x, _w in zip( x, w ) ] )
or in 2.4
sum( _x * _w for _x, _w in zip( x, w ) )
You may want to use itertools.izip in place of zip if the lists are large.
Will McGugan
--
http://mail.python.org/mailman/listinfo/python-list


Re: computing a weighted sum

2005-03-16 Thread Duncan Booth
 wrote:

 Suppose I have a list of n floats x and a list of n floats w and I want
 to compute x[0]*w[0] + .. + x[n-1]*w[n-1].
 
 Is there some elegant expression (perhaps using lambda) to have it done
 in one statement ? As in :
  y = lambda x,w : ...

 x = [1, 2, 3]
 w = [4, 5, 6]
 sum(a*b for (a,b) in zip(x, w))
32
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting current variable name

2005-03-16 Thread Daniel Dittmar
pl wrote:
I have to get some list variable names at some point in my program. So
I ended up looking into globals() to get them with a small function like
this:
[...]
var = globals().keys()
for i in var :
if globdict[i] == obj:
print i
Use 'is' instead of '=='. This will return true if the arguments are the 
same object:
 l1 = [1, 2, 3]
 l2 = [1, 2, 3]
 l1 == l2
True
 l1 is l2
False

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


Re: Why tuple with one item is no tuple

2005-03-16 Thread Diez B. Roggisch
 That ambiguity is only caused because python uses the same characters
 for very different operations and to be honest I don't like that.

As I said: show me which parentheses to use - and keep in mind that:

 -  and  are for comparisions and the same ambiguity troubles arise 
 - unicode surely features some usable characters (e.g. the quotation markes
that look like , but are one char). But for one that complains that
typing and additional comma is too much already, I doubt that having to
press some weird multi key stroke is a viable option. To me neither, as I
prefer my parentheses to be accessed easily, even on a vi running in a
console from a tn3270 terminal


 
 for instance I have written once somekind of vector class where
 it was natural for these vectors to be added as well as te be
 concatenated. Unfortunately python uses + for both so I had
 no way to have both operators in a natural way in python.

And no way in mathematics or any other language either - if you want the
same function symbol on the same operators to have _different_ semantics,
you're getting pretty non-deterministic.


 
 So that a * would create an ambiguity if items would be silently
 transformed in a one-item tuple when appropiate is IMO more caused
 by the design decision to use * for two totally diffent operations
 then because of the dynamic nature of python.

Your opinion is wrong. It's because you seem to not have understood the
example: The expression (5 + 4) could be understood as 9 or as (9,). In
python (and each and every other dynamically typed language) you can't
decide which version to take. So you have to decide on _one_, and as every
kid in school learns that (5+4) * 5 is 45, it was a reasonable decision to
use the semantics we have today.

In a statically typed language, (5+4) _could_ be the tuple if the expression
is used in a typing context that makes that determinable. An example would
be

list((5+4))

as the list constructor needs a iterable to work, so it would be declared
like this:

list _ : [ iterable[alpha] ] - list[alpha]

But then you'd have to forbid overloading of operators, or someone could
declare a list like this:

list _ : [ num ] - list[int]

to create lists of zeros of type int. Which would reintroduce the ambiguity
again.


 And if the static typed language allows operator overloading, it could
 very well be that someone creates a overloading for

* : [tuple[num], tuple[num]] - whatever

 which would reintroduce the ambiguity.

 Soo, in the end it boils down to some explicitness - where IMHO an
 additional comma is pretty much no problem at all. Another option would
 of course be the introduction of different parentheses for tuples - but I
 can't find some on my keyboard.
 
 Well I can't find braille on my keyboard, but if I wanted to, it
 wouldn't be difficult to get it on my screen. So is it with
 different parentheses. That python can't use these parentheses
 is again a design decision.

For someone who expresses his disliking to type _one_ comma in the few cases
of single element tuples in thousands of lines of code, it strikes me odd
that you'd go an are willing to add extra trouble entering _each_ and
_every_ tuple in your code by using some hitherto unknown character that
won't be enterable easily 

But you showed that strange sense of reasoning before - I remember you
wanting to shave off microseconds by optimising constant expressions like
5*4 whilst at the same time arguing in another thread that you'd like to
have mutable keys for dicts that needed copying the very same keys - at
much greater costs, per case and even more so in general as using dicts is
common where pure constant arithmetic expressions aren't.


-- 
Regards,

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


Re: Good use for Jython

2005-03-16 Thread Tom Willis
On 15 Mar 2005 23:54:16 -0800, Mike Wimpe [EMAIL PROTECTED] wrote:
 Other than being used to wrap Java classes, what other real use is
 there for Jython being that Python has many other GUI toolkits
 available? Also, these toolkits like Tkinter are so much better for
 client usage (and faster) than Swing, so what would be the advantage
 for using Jython? or Is Jython really just so that Java developers can
 write Java code faster?
 
 Mike Wimpe
 
 --
 http://mail.python.org/mailman/listinfo/python-list
 

I haven't done anything substatial with Jython yet, but I consder it
to be valuable in areas where you have to do something quick and
dirty, perhaps debug an EJB running on an app server for example.

Bean shell serves the same purpose and the syntax is pretty much Java
so the learning curve isn't as steep for java developers.

I see it as a way of getting around some of the requirements of the
language. If I needed to connect to java systems together and I needed
to do it quickly, and the quality of requirements was less than
adequate, I'd rather write a script(beanshell/jython/groovy) than
booting up eclipse and contributing to the interface cesspool .

-- 
Thomas G. Willis
http://paperbackmusic.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: computing a weighted sum

2005-03-16 Thread andreif
Thanks Will, the 2.4 expression looks really nice.

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


Re: Turning String into Numerical Equation

2005-03-16 Thread Steven Bethard
Giovanni Bajo wrote:
In fact, the documentation for eval() could be improved to explain the benefits
of setting __builtins__ in the globals.
Well, if you think you're pretty clear on what's happening, a patch is 
always appreciated. =)  I have a feeling that the docs are at least 
partially vague because no one actually wants to advertise the 
restricted execution features[1] since no one can guarantee that they're 
really secure...

STeVe
[1] Guido say as much 
http://mail.python.org/pipermail/python-dev/2002-December/031234.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: computing a weighted sum

2005-03-16 Thread TZOTZIOY
On 16 Mar 2005 06:49:09 -0800, rumours say that [EMAIL PROTECTED] might have
written:

Suppose I have a list of n floats x and a list of n floats w and I want
to compute x[0]*w[0] + .. + x[n-1]*w[n-1].

Is there some elegant expression (perhaps using lambda) to have it done
in one statement ? As in :
 y = lambda x,w : ...

I ask because the way I am doing it now :
  y = 0
  for i in range(0,n): y += x[i]*w[i]

doesn't seem very pythonic :)

Your method seems to be the one closest to what's generally considered as
pythonic.

Anyway, a functional equivalent:

. from itertools import starmap, izip
. import operator
. x= [1,2,3,4]
. w=[3.0, 6.0, 9.0, 12.0]
. sum(starmap(operator.mul, izip(x,w)))
90.0
.
-- 
TZOTZIOY, I speak England very best.
Be strict when sending and tolerant when receiving. (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why tuple with one item is no tuple

2005-03-16 Thread Daniel Dittmar
Diez B. Roggisch wrote:
for instance I have written once somekind of vector class where
it was natural for these vectors to be added as well as te be
concatenated. Unfortunately python uses + for both so I had
no way to have both operators in a natural way in python.

And no way in mathematics or any other language either - if you want the
same function symbol on the same operators to have _different_ semantics,
you're getting pretty non-deterministic.
I think he meant that Python should have introduced different operators 
for addition and sequence concatenation.

Your opinion is wrong. It's because you seem to not have understood the
example: The expression (5 + 4) could be understood as 9 or as (9,). In
It should be understood as 9, but if integers etc implement the sequence 
protocol, 9 can be used just like a tuple 
(http://www.livejournal.com/users/glyf/29038.html).

There have been other proposals where you could write 'for i in 5' etc.
I find this 'creative use of overloading' rather awful. But what the 
heck, I find list comprehension rather awful.

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


Re: Getting current variable name

2005-03-16 Thread Steven Bethard
pl wrote:
I followed the mails entitled 'How to turn a variable name into a
string?' in march 2005 posts as I have a similar problem.
I have to get some list variable names at some point in my program. So
I ended up looking into globals() to get them with a small function like
this:
#!/usr/bin/python
l1 = ['r', 'r', 't']
l2 = ['r', 't', 't']
l3 = ['t', 't', 't']# Two equivalent lists but...
l4 = ['t', 't', 't']# with different names
def nameofObj(obj):
#   print locals()
globdict = globals()
var = globals().keys()
for i in var :
if globdict[i] == obj:
print i
print '-'*20 ,'\n'
nameofObj(l1)
print '-'*20 ,'\n'
map(nameofObj, [l1, l2, l3, l4])
What is the problem you're trying to solve here?  Looking up the names 
of an object is not usually something you want to do.  If you provide a 
little more detail on your use case, we might be able to help you 
refactor this code.

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


Re: computing a weighted sum

2005-03-16 Thread Steven Bethard
Will McGugan wrote:
In Python 2.3
sum( [ _x * _w for _x, _w in zip( x, w ) ] )
or in 2.4
sum( _x * _w for _x, _w in zip( x, w ) )
Any reason for the leading underscores?  If you're trying to avoid 
polluting your namespace, you should note that generator expressions 
don't leak their loop variables, so you can write the second as:

sum(x*w for x, w in zip(x, w))
without any worries of overwriting x and w.  (Of course I would probably 
name them something different anyway, e.g. x_item and w_item...)

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


Re: Why tuple with one item is no tuple

2005-03-16 Thread Steven Bethard
Daniel Dittmar wrote:
But what the heck, I find list comprehension rather awful.
Sacrilege! ;)
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why tuple with one item is no tuple

2005-03-16 Thread Diez B. Roggisch
 I think he meant that Python should have introduced different operators
 for addition and sequence concatenation.

I reread his example and have to admit I'm confused: He complains about
having written his _own_ vector class - and concatenation and addition had
to use both + ?

He could have used | for concatenation instead. Apart from the concatenation
IMHO not being a mathematical founded operation on vectors.

I maybe was confused of him using + as bad example and then extending that
to *. But even more so my point is valid: If you forbid the overloading of
operators, you have to come up with even _more_ operator names, like ocaml
has *. and * for multiplication of floats and ints. So you end up with way
more clutter in the source, certainly more than the occasional extra comma.

 Your opinion is wrong. It's because you seem to not have understood the
 example: The expression (5 + 4) could be understood as 9 or as (9,). In
 
 It should be understood as 9, but if integers etc implement the sequence
 protocol, 9 can be used just like a tuple
 (http://www.livejournal.com/users/glyf/29038.html).

The examples focus too much on numbers - if we use instead 

(foo)

we would get a iterable yielding [foo,] or - as string already supports
iteration - ['f', 'o', 'o']. Which one to chose?

 
 There have been other proposals where you could write 'for i in 5' etc.
 
 I find this 'creative use of overloading' rather awful. But what the
 heck, I find list comprehension rather awful.

Well, the number of operators built into the language is limited - and I
actually prefer to have the possibility to overload these if I want to.
Nobody forces me - I could use

v1.concat(v2)

for two vectors v1, v2 if I wanted to.


-- 
Regards,

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


Writing C readable bitfield structs?

2005-03-16 Thread phark52
How would I go about writing a bitfield that can be read by my C app? I
want to pack a few bools into one int.

I know an extended module exists (npstruct) which helps you do this but
I want to do it manually or using one of the standard modules.

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


Mark attribute as read-only

2005-03-16 Thread Florian Lindner
Hello,
how can I mark a attribute of a class as read-only (for non classmembers)?
Yes, stupid question, but the docu gave me no help.

Thanks,

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


[OT] Re: Python becoming less Lisp-like

2005-03-16 Thread Brian van den Broek
news.sydney.pipenetworks.com said unto the world upon 2005-03-16 05:57:
SNIP
trust the guy to do a good job. If you don't, then you can write it 
yourself which means you can do exactly how you want it which again 
makes the whole argument mute.
Anyone else having images of mimes engaged in street fights? ;-)
Best,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: computing a weighted sum

2005-03-16 Thread andreif
Even if language permits
  sum(x*w for x, w in zip(x, w))
would seem confusing for anyone watching the code

Maybe
   sum(xi*wi for xi, wi in zip(x, w)) 
would be more appropiate

Andrei

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


How to add a shapefile to an existing ArcMap 9.x project using Python?

2005-03-16 Thread syed_saqib_ali
Hi.


I have an Instance of ArcMap 9.0 running.


I also have a shapefile named myShape (actually corresponding to 4
files on the disk: myShape.dbf, myShape.shp, myShape.pnt and
myShape.shx)


I would like to write some Python code that inserts myShape into the
running instance of ArcMap9.0 as a new layer.


How can I do this? What software tools/package can I use to do this?
Can you show me the Python code fragment? 


Thanks 
-Saqib

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


Re: Minidom empty script element bug

2005-03-16 Thread Derek Basch
Cross post from XML-SIG:

--- Walter Dörwald [EMAIL PROTECTED] wrote:
 Martin v. Löwis sagte:
  Derek Basch wrote:
  [...]
  How do I get minidom to NOT render an empty script element? Should
I
 submit a bug report?
 
  That said, I think there is a simple solution: add an empty Text
node to
 the script element:
 
  script_node_0.appendChild(doc.createText(u))
 
  [Disclaimer: this is untested; from reading the source, I think it
should
 work]

 If this doesn't work, you might want to try XIST
 (http://www.livinglogic.de/Python/xist)
 instead of minidom. XIST knows that the script element is not EMPTY,
and when
 the
 output is in HTML compatible XML an end tag will be produced:

  from ll.xist.ns import html
  print html.script(type=text/javascript,
 src=../test.js).asBytes(xhtml=1)
 script src=../test.js type=text/javascript/script

 Using pure XML mode gives:

  print html.script(type=text/javascript,
 src=../test.js).asBytes(xhtml=2)
 script src=../test.js type=text/javascript/

 Bye,
Walter Dörwald

Wow! XIST is very elegant. Perfectly designed for what it is supposed
to do.

XIST is an extensible HTML/XML generator written in Python.

I guess there isn't much point in fixing the pyXML XHTMLPrinter when
something as cool as XIST exists (pun intended).

Kid also seems really neat. I like the TAL like features. However, it
seems less mature than XIST.

There seems to be lots of functionality crossover between the two but
it is good that there is enough demand for XML output functionality in
python to support two distinct modules.

Thanks Everyone!,
Derek Basch

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


Re: Mark attribute as read-only

2005-03-16 Thread Steven Bethard
Florian Lindner wrote:
how can I mark a attribute of a class as read-only (for non classmembers)?
Yes, stupid question, but the docu gave me no help.
Declare it as such in the documentation. ;)
If you want to provide error messages, you could alternatively define a 
property:

py class C(object):
... def _getx(self):
... return self._x
... x = property(fget=_getx)
... def __init__(self, x):
... self._x = x
...
py c = C(4)
py c.x
4
py c.x = 6
Traceback (most recent call last):
  File interactive input, line 1, in ?
AttributeError: can't set attribute
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: __getitem__ method on (meta)classes

2005-03-16 Thread Ron Garret
In article [EMAIL PROTECTED],
 Steven Bethard [EMAIL PROTECTED] wrote:

 Ron Garret wrote:
  In article [EMAIL PROTECTED],
   Steven Bethard [EMAIL PROTECTED] wrote:
  
 Yeah, except I actually left out one thing:  I also want type(v)==e1.
 
 Why?  In Python usually you rely on duck-typing and not explicit type 
 checks.  What is it that you're trying to gain by asserting type(v) == e1?
  
  Clarity.  I want to be able to distinguish a member of an enumeration 
  from a string or an integer for the same reason one would want to 
  distinguish 123 from 123.
 
 So then you don't necessarily need that type(v) == e1, you just need 
 type(v) != str.  How about:

[xnip]

That's not bad.  This conflates all enumerated items into a single 
namespace whereas the metaclass solution makes each enumeration its own 
namespace.  For example:

plumbers = enum['Fred','John','Bill']
electricians = enum['Fred','Jake','Lester']

Using a metaclass allows you to distinguish Fred the plumber from Fred 
the electrician.  But that may or may not be what one actually wants.

Must sleep on it.

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


Re: Writing C readable bitfield structs?

2005-03-16 Thread Larry Bates
[EMAIL PROTECTED] wrote:
 How would I go about writing a bitfield that can be read by my C app? I
 want to pack a few bools into one int.
 
 I know an extended module exists (npstruct) which helps you do this but
 I want to do it manually or using one of the standard modules.
 
struct.pack is in the Standard Library and allows you to do what
you want.  You may find that you must also do some bit twiddling
using  shift functions and | bit or function if you want to pack
tighter than on 4 bit boundaries.

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


_conditionally_ returning to point where exception was raised?

2005-03-16 Thread MackS
Hi

I'm new to Python and would like to know if the following is possible.

Say I have one lower-level object A and one user-interface object B.
Suppose B.CallingMethod() calls A.CalledMethod(), the latter method
stumbles upon an IO error and raises an exception. The calling method
detects the exception, but needs to get input from the user before
deciding whether A.CalledMethod() should continue being executed or
permantently stop/cancel the execution of the remaining code in
A.CalledMethod(). Can this be done?

What I would like to know is if the calling method is allowed to
decide (at run-time) whether or not the execution of the called
method resumes. Until now I only see two possibilities: either the
caller is coded in a way that it handles the exception and execution of
the called method resumes at the point where the exception was raised
or the caller was written in a way that doesn't handle it and the
program is stopped by the interpreter. Is there a third way, ie is it
possible to determine at run-time whether the called method is resumed?

Thanks in advance,

Mack Stevenson

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


Re: will it cause any problems to open a read-only file not close it?

2005-03-16 Thread Jeff Shannon
Tim Roberts wrote:
Sara Khalatbari [EMAIL PROTECTED] wrote:

Dear friends
In a code, I'm opening a file to read. Like :
  lines = open(filename).readlines()
 I'm never closing it.
I'm not writing in that file, I just read it.
Will it cause any problems if you open a file to read
 never close it?
A file is closed when the last reference to it is deleted.  Since you never
save a reference to this file, the last reference is deleted as soon as the
readlines() call finishes.
So, the file will be closed when you move to the next statement.
This is true in current versions of CPython, but is not necessarily 
true in all implementations of Python.  In particular, Jython uses 
Java's garbage collector; an object becomes available for collection 
when the last reference is deleted, but that collection may not 
(probably won't) happen right away.  Since the automatic file closing 
happens as part of the object deletion, files opened in this way won't 
 be closed until the garbage collector runs (and collects this file 
object).

Most of the time, this won't be a problem, but it's good to be aware 
that things are not necessarily as cut-and-dried as they might seem.

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


Re: [OT] Who Knows of a Good Computational Physics Textbook?

2005-03-16 Thread Dan Sommers

Thank you beliavsky, Sean, and Scott for the pointers.

Regards,
Dan

-- 
Dan Sommers
http://www.tombstonezero.net/dan/
c = 1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code for Computer Language Shootout

2005-03-16 Thread Michael Spencer
F. Petitjean wrote:
Le Tue, 15 Mar 2005 23:21:02 -0800, Michael Spencer a écrit :

def output(seq, linelength = 60):
if seq:
iterseq = iter(seq)
while iterseq:
print .join(islice(iterseq,linelength))
I suppose you mean :
   print .join( str(item) for item in islice(iterseq, linelength) )
   #  using python 2.4 genexp
No, as written, given the seq is a sequence of single character strings already 
(changing the signature might clarify that):

def output(charseq, linelength = 60):
if charseq:
iterseq = iter(charseq)
while iterseq:
print .join(islice(iterseq,linelength))
  output(* * 120, 40)
 
 
 
  output(['*'] * 120, 40)
 
 
 
 
Cheers
Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python becoming less Lisp-like

2005-03-16 Thread Kay Schluehr
Torsten Bronger wrote:
 Hallöchen!

Moin!

 [First, I wanted to say descriptors instead of decorators (I
 superseded my post).]

 The goal is to trigger function calls when attributes are accessed.
 This is called properties in C# (and maybe in Ruby, too).  Python
 now also has this concept.  What I find ugly is that it is not a
 syntax element.  It looks artificially added to the language.  In
 C#, the set and get methods form with its attribute a syntactic
 unity.  Everything is together, and no property function is
 necessary.

Some people refused properties in Python for exactly this reason.
Defining somewhat like:

def _get_X(self):
return self._X

def _set_X(self,X):
self._X = X

X = property(_get_X, _set_X )

in a Java-style fashion is indeed awfull and clumsy and that people
dismiss such boilerplate code is understandable.

But Thinking in Java in Python is probably no good idea allthough
this style can be found in Guidos property-examples presented in his
famous introduction on new-style classes as well:

http://www.python.org/2.2/descrintro.html

I thought for a long time that C# solved this problem with a superior
accurate and compact notion, but paying more attention to the
property() function itself and not to the declarative style getters and
setters opened me a more generic road to reason about desciptors:

def accessor(name, check=None, types=[]):
'''
Generic property creator.
'''
name  = __+name
def get(obj):
if not hasattr(obj,name):
setattr(obj,name, None)
return getattr(obj,name)

def set(obj,value):
if types:
if not True in [isinstance(value,t) for t in types]:
raise TypeError, Can't assign %s to property
%s.%(value,name[2:])
if check:
if not check(value):
   raise TypeError, Can't assign %s to property
%s.%(value,name[2:])
else:
setattr(obj,name,value)
return property(get,set,None)



Now an example:


class X(object):
a = accessor(a)
b = accessor(b, types = (tuple,list))
c = accessor(c, check = lambda x:hasattr(x,__len__))

a,b,c are indeed properties of X !

 x = X()
 x.b = [1,2,3] # o.k
 x.b
[1, 2, 3]
 x.b = 0  # raises a TypeError, because a tuple/list is expected
.
.


Regards Kay

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


importerror all 3rd party modules

2005-03-16 Thread nyiann
Hi,
Brand new to python.  I am trying to install the py2exe modeule, and when 
I run scripts (simple ones I've made, and examples) I get an importerror. 
At the python command line I type:
import py2exe
and get: 'ImportError: no module named py2exe

So installed everything on my laptop (windows me) and it all works fine.
Has anyone seen this before?  Am I importing the module incorrectly?  Are 
there platform specifics issues when installing 3rd party modules?

Any suggestions appreciated,
N
--
http://mail.python.org/mailman/listinfo/python-list


Access denied calling FireEvent in Python

2005-03-16 Thread calfdog
Hello,

Does anyone know a workaround for calling fireEvent.
With the latest from Microsoft OS XP2 and Hot fixes to
IE it now gives an access denied error in Python when called.

Here is what I am trying to do:
Set the campus listbox value and theb call fire event, such as in the
code below.  I get an access denied error.

example code:
ie = DispatchEx('InternetExplorer.Application')

# Some code to navigate to the site, wait till doc is not busy and #
ReadyState is complete...blah..blah...

ie.Document.forms[0].campus.value = '200'
ie.Document.forms[0].campus.fireEvent('onchange')

HTML code:
select style=font-size: 10 name=campus onChange=if
(this.options[this.selectedIndex].value != 0)
populate(this.options[this.selectedIndex].value)
option value=0Select a campus
option value=200Norman Campus
option value=501Advanced Programs
option value=502Liberal Studies
option value=504Academic Programs (CAFE)
option value=505OU Tulsa/select


If you call:
fireEvent('onchange')
fireEvent('onclick')
fireEvent('onFocus') etc... You will get an Access Denied

This only happens with either the newer version of IE and XP2.
I was able to call the exact same code with XP1 and Win2000 Pro
and it work fine. So something has changed with I.E. and is not being
handled in Python.


example code:
ie.Document.forms[0].campus.fireEvent('onchange')

Trace:
 File
C:\Python23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py,
line 310, in RunScript
exec codeObject in __main__.__dict__
  File C:\QA\Tools\cPAMIE150\oCScript2.py, line 24, in ?
ie2.Document.forms[0].campus.fireEvent('onchange')
  File C:\Python23\Lib\site-packages\win32com\client\dynamic.py, line
165, in __call__
return
self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
com_error: (-2147024891, 'Access is denied.', None, None)

Help would be much appreciated!!

RLM

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


Re: _conditionally_ returning to point where exception was raised?

2005-03-16 Thread infidel
There's no Resume Next in python.  Once you catch an exception, the
only way you can go is forward from that point.

So if B.CallingMethod catches an exception that was raised in
A.CalledMethod, all it could do is try calling A.CalledMethod again, it
can't jump back to the point where the exception was raised.  About the
best you could, I think, would be to break A.CalledMethod up into
smaller function and let B.CallingMethod call each one in sequence,
deciding whether or not to continue if an exception is raised in any of
them.

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


Re: _conditionally_ returning to point where exception was raised?

2005-03-16 Thread Bengt Richter
On 16 Mar 2005 09:53:11 -0800, MackS [EMAIL PROTECTED] wrote:

Hi

I'm new to Python and would like to know if the following is possible.

Say I have one lower-level object A and one user-interface object B.
Suppose B.CallingMethod() calls A.CalledMethod(), the latter method
stumbles upon an IO error and raises an exception. The calling method
detects the exception, but needs to get input from the user before
deciding whether A.CalledMethod() should continue being executed or
permantently stop/cancel the execution of the remaining code in
A.CalledMethod(). Can this be done?

What I would like to know is if the calling method is allowed to
decide (at run-time) whether or not the execution of the called
method resumes. Until now I only see two possibilities: either the
caller is coded in a way that it handles the exception and execution of
the called method resumes at the point where the exception was raised
or the caller was written in a way that doesn't handle it and the
program is stopped by the interpreter. Is there a third way, ie is it
possible to determine at run-time whether the called method is resumed?

Thanks in advance,

Once an exception is raised, the stack gets unwound to the point where
the exception is caught, so there is no way[1] to recover the context required
to continue (and eventually return normally as if the exception hadn't 
happened).

One way to preserve the stack is to call a call-back function instead of raising
an exception. Then the call-back could return some information (e.g. user 
input) to
the problem context to make decisions as to how to continue (or not), or the 
callback
itself could also raise an exception.

But then the caller has to be able to provide a call-back function one way or 
another.
If you are designing the whole thing, you can do it, but if you are calling low 
level
services that you can't change, and which raise exceptions, then you may have 
some
fancy wrapping to do to create your desired interface, if it is even possible.

[1] Just to note that I know it is not wise to say no way on c.l.py, since 
you never
know what clever people will come up with ;-) Maybe someone will create a way 
for an
exception to return a continuation object of some kind, that could optionally 
be called
from the exception handler to effect as-if return to the point of an exception 
and
continuation from there as if the exception hadn't happened (except maybe some 
updated
binding in the local context that could be seen by the continuing code, and be 
set via
the contination-object call). I have a hunch it's possible, but pretty hairy.

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


When is a thread garbage collected?

2005-03-16 Thread Kent Johnson
If I create and start a thread without keeping a reference to the thread, when is the thread garbage 
collected?

What I would like is for the thread to run to completion, then be GCed. I can't find anything in the 
docs that specifies this behavior; nor can I think of any other behaviour that seems reasonable :-)

For example with this code:
def genpassenger(num):
for i in range(num):
passenger().start()
class passenger(threading.Thread):
def run:
#do something
will all the passenger threads run to completion, then be GCed?
Thanks,
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: Writing C readable bitfield structs?

2005-03-16 Thread Cappy2112
there is a bitfiled mainpulator class inthe Cookbook, but I don't
understand his explanation, and the example given doesn't really show
off the features of the class.

I too need bit-level manipulation, and will probably have to write my
own class to do it.

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


Re: Writing C readable bitfield structs?

2005-03-16 Thread Roy Smith
In article [EMAIL PROTECTED],
Cappy2112 [EMAIL PROTECTED] wrote:
there is a bitfiled mainpulator class inthe Cookbook, but I don't
understand his explanation, and the example given doesn't really show
off the features of the class.

I assume you're talking about the struct module?  If you give an
example of the C struct you're trying to read/write, I could come up
with some sample code to do it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Turning String into Numerical Equation

2005-03-16 Thread Michael Spencer
Giovanni Bajo wrote:
Michael Spencer wrote:

In fact, I believe my solution to be totally safe,
That's a bold claim!  I'll readily concede that I can't access
func_globals from restricted mode eval (others may know better).  But
your interpreter is still be vulnerable to DOS-style attack from
rogue calculations or quasi-infinite loops.

Yes, but I don't see your manually-rolled-up expression calculator being
DOS-safe. I believe DOS attacks to be a problem whenever you want to calculate
the result of an expression taken from the outside. What I was trying to show
is that my simple one-liner is no worse than a multi-page full-blown expression
parser and interpreter.
Fair point that brevity is itself valuable in achieving security.  It isn't 
worth using my manually-rolled-up expression calculator simply to deny access 
to func_globals as you have demonstrated.

However, the advantage of the MRUEP is that every operation is evaluated 
individually.  In the example I showed, loops are disabled, attribute access is 
disabled.  Numeric inputs and intermediate results can be checked easily for 
boundedness (though they are not in the example I gave).  This sort of 
fine-grain control is very much harder to do with a straight eval model.

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


Re: newbie : modifying a string in python

2005-03-16 Thread Brian van den Broek
Leeds, Mark said unto the world upon 2005-03-16 14:46:
I want to modify a string in the following way :
 

for s in stks:
  s = s.strip()
  if ( s[-2:] == 'GR' ):
  s[-2:]= 'GF'
 

so, if the last two characters are GR, I want to change
them to GF ( there will be other if statements also but I am
just putting this one here for simplicity ).
 

I think the code is fine but I vaguely remember
reading somewhere in the documentation that
python strings can't be changed ( only elements of lists can be ) ?.
Is that true or is it okay to do the above.
.
   thanks
Hi Mark,
well, what happens when you try?
 test_string = 'some text ending in GR'
 if test_string[-2:] == 'GR':
... test_string[-2:] = 'GF'
...
Traceback (most recent call last):
  File interactive input, line 2, in ?
TypeError: object doesn't support slice assignment
So, not so much :-)
You can do it thusly:
 if test_string[-2:] == 'GR':
... test_string = test_string[:-2] + 'GF'
...
 test_string
'some text ending in GF'
But, a better way in that it uses .endswith and points towards 
generalization:

 old_chars = 'GR'
 new_chars = 'GF'
 test_string = 'some text ending in GR'
 if test_string.endswith(old_chars):
... test_string = test_string[:-len(old_chars)] + new_chars
...
 test_string
'some text ending in GF'

Wrap that in a function:
def replace_at_end(string, old, new):
# logic here with a return of the new string as the last line
and you've got something reusable :-)
(There may be better ways, still; I'm no expert :-)
HTH,
Brian vdB
--
http://mail.python.org/mailman/listinfo/python-list


Re: _conditionally_ returning to point where exception was raised?

2005-03-16 Thread Skip Montanaro

 ... The calling method detects the exception, but needs to get input
 from the user before deciding whether A.CalledMethod() should
 continue being executed or permantently stop/cancel the execution of
 the remaining code in A.CalledMethod(). Can this be done?

Bengt Once an exception is raised, the stack gets unwound to the point
Bengt where the exception is caught, so there is no way[1] to recover
Bengt the context required to continue (and eventually return
Bengt normally as if the exception hadn't happened).

I suspect in the OP's case if A.CalledMethod hasn't gone too far before
encountering an IOError it's quite reasonable to thing that B.CallingMethod
just call A.CalledMethod again if it decides to continue.

I will point out that someone posted some autoload code here awhile ago
(who was it?) to try to import missing modules.  I use a variant in my
Python startup file:

% python
Python 2.5a0 (#75, Mar 15 2005, 21:55:51) 
[GCC 3.3 20030304 (Apple Computer, Inc. build 1671)] on darwin
Type help, copyright, credits or license for more information.
 print sin(5)
found sin in math module
-0.958924274663
 conn = MySQLdb.Connection
autoloading MySQLdb
 conn
function Connect at 0x136abb0

After finding the module that needs to be imported, it reexecutes the code
object for the frame where the exception was raised:

exec import_stmt in f_locals, f_globals
exec tb.tb_frame.f_code in f_locals, f_globals

That's not exactly what the OP asked for (it executes the code object from
the beginning, not from the point where the exception was raised with
possibly modified locals and globals), but might provide people with some
ideas.  The full autoload module is at

http://manatee.mojam.com/~skip/python/autoload.py

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


newbie : modifying a string in python

2005-03-16 Thread Leeds, Mark








I want to modify a string in the following way :



for s in stks:

 s = s.strip()

 if ( s[-2:] == GR
):


s[-2:]= GF



so, if the last two characters are GR, I want to change

them to GF ( there will be other if statements also but I am

just putting this one here for simplicity ).



I think the code is fine but I vaguely remember

reading somewhere in the documentation that

python strings cant be changed ( only elements of
lists can be ) ?.

Is that true or is it okay to do the above.

.


thanks






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

  1   2   >