Requesting direction for installation problem

2008-11-26 Thread Frederic Rentsch

Hi,

Where can one get assistance if a Windows installation service fails to 
install an msi installer? I used to download zip files, but they seem to 
have been replaced with msi files. I know this issue is off topic here. 
So my question simply is: where is it not off topic?


Thanks for any hint

Frederic

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


Re: what's so difficult about namespace?

2008-11-26 Thread Stefan Behnel
Glenn Linderman wrote:
 it appears the
 OP understands that issue, and is asking why languages without
 namespaces don't add them.

Note that Xah Lee is not generally someone who (or something that) asks
in order to learn something or to understand issues better. The more
general interest appears to be spreading controversial topics over a vast
number of newsgroups.

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


Re: Reg Expression - Get position of

2008-11-26 Thread Duncan Booth
Chris Rebert [EMAIL PROTECTED] wrote:

 On Wed, Nov 26, 2008 at 1:48 AM, M_H [EMAIL PROTECTED]

 I have a beginning of a (longer) string who is like:
 mystr =  'mimetype=text/htmlcontent![CDATA['
 or like
 mystr =  'mimetype=text/html content![CDATA['
 or like
 mystr =  'mimetype=text/html 
  NewLine content![CDATA['

 
 Any particular reason you're not using an HTML parser (e.g.
 BeautifulSoup) ? 
 
It might possibly be because any kind of HTML or XML parser is going to get 
indigestion when fed a tag name followed by an equal sign.

However, a good question to the OP might be is there any particular reason 
your data looks vaguely xml like but isn't?

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to get a directory file descriptor?

2008-11-26 Thread Cong Ma
alex23 wrote:
 On Nov 26, 3:26 pm, greg [EMAIL PROTECTED] wrote:
 os.O_DIRECTORY must be fairly new -- it doesn't exist
 in my 2.5 installation. But os.O_RDONLY seems to work
 just as well for this purpose.
 
 Which OS are you using?
 
 Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
 [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
 Type help, copyright, credits or license for more information.
 import os
 hasattr(os, 'O_DIRECTORY')
 True
 
 I'm pretty certain it was present under Windows XP as well.
 
 
 --
 http://mail.python.org/mailman/listinfo/python-list
 
Hello,

Thanks for your reply. I checked my Python 2.5 install on Linux and there's the
O_DIRECTORY flag. However this is not mentioned anywhere in the Library 
Reference.

There's another question regarding to this flag though: I checked the manual of
the Linux system call open(2), in which there's a paragraph on this flag:

   O_DIRECTORY
  If pathname is not a directory, cause the open  to  fail.   This
  flag is Linux-specific, and was added in kernel version 2.1.126,
  to avoid denial-of-service problems if opendir(3) is called on a
  FIFO  or  tape  device,  but  should  not be used outside of the
  implementation of opendir(3).

Note the should not be used outside of the implementation of opendir(3) part.
Does that mean using Python's os.open() with the O_DIRECTORY flag is a Bad
Thing? In C, I think, calling opendir() followed by dirfd() should be the
correct way of doing this?

Thanks.

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


Tkinter and asyncronous socket

2008-11-26 Thread maxlosblob
Hi all, I'm new to python and I've been spending the last week on GUI
that refresh its content based on data periodically coming from a
remote socket.
I succeded in doing it (thanks newsgroups and online manual!) using
the Tkinter.after method to implement a busy wait on the socket (which
I had previously set to non blocking)
I should be happy with it, but on windows (application must be multi-
platform) the busy wait leads to a 100% CPU usage. I'm trying to
implement it the other way round: a socket process that updates a
label (or a queue object) in the GUI. I can't figure out how to do
this. Anyone can post hints? With some details, maybe?

Thanks all

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


Re: Python C/API simple debugging

2008-11-26 Thread Stefan Behnel
k3xji wrote:
 I am new to Python C API and finding it difficult to debug C
 extensions. So, basically I want to see the value of an integer value
 during the C API. Here is the code:
 
 #define LAST_MIX_VAL 0xDEADBEEF
 
 static PyObject *
 chash(PyObject *self, PyObject *args)
 {
 unsigned int key,result; //treat key like an usinged int.
   unsigned char a,b,c,d;
 
   key = result = 0;
 if (!PyArg_ParseTuple(args, i, key))
 return NULL;
 
   printf(Key:%i\n,Py_BuildValue(i, key));
   .
 .
 [...]
 - What is the preffered approach for these kind simple-debugging
 issue?

If you want to simplify this kind of debugging as well as the general code
writing itself, consider using Cython.

http://cython.org/

Apart from that, I'd use gdb for debugging these things. It does have a
learning curve, but in change gives you a lot more than just print-debugging.

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


Re: Python C/API simple debugging

2008-11-26 Thread k3xji
On Nov 26, 1:34 pm, Stefan Behnel [EMAIL PROTECTED] wrote:
 k3xji wrote:
  I am new to Python C API and finding it difficult to debug C
  extensions. So, basically I want to see the value of an integer value
  during the C API. Here is the code:

  #define LAST_MIX_VAL 0xDEADBEEF

  static PyObject *
  chash(PyObject *self, PyObject *args)
  {
      unsigned int key,result; //treat key like an usinged int.
     unsigned char a,b,c,d;

     key = result = 0;
      if (!PyArg_ParseTuple(args, i, key))
          return NULL;

     printf(Key:%i\n,Py_BuildValue(i, key));
     .
  .
  [...]
  - What is the preffered approach for these kind simple-debugging
  issue?

 If you want to simplify this kind of debugging as well as the general code
 writing itself, consider using Cython.

 http://cython.org/

 Apart from that, I'd use gdb for debugging these things. It does have a
 learning curve, but in change gives you a lot more than just 
 print-debugging.

 Stefan

OK.

How to use gdb? I am compiling the extension to a pyd file and
importing it right now. So, I assume we need to, somehow load the
extension dynamically for debugging? But how?

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


Re: Python C/API simple debugging

2008-11-26 Thread Diez B. Roggisch
k3xji wrote:

 On Nov 26, 1:34 pm, Stefan Behnel [EMAIL PROTECTED] wrote:
 k3xji wrote:
  I am new to Python C API and finding it difficult to debug C
  extensions. So, basically I want to see the value of an integer value
  during the C API. Here is the code:

  #define LAST_MIX_VAL 0xDEADBEEF

  static PyObject *
  chash(PyObject *self, PyObject *args)
  {
  unsigned int key,result; //treat key like an usinged int.
  unsigned char a,b,c,d;

  key = result = 0;
  if (!PyArg_ParseTuple(args, i, key))
  return NULL;

  printf(Key:%i\n,Py_BuildValue(i, key));
  .
  .
  [...]
  - What is the preffered approach for these kind simple-debugging
  issue?

 If you want to simplify this kind of debugging as well as the general
 code writing itself, consider using Cython.

 http://cython.org/

 Apart from that, I'd use gdb for debugging these things. It does have a
 learning curve, but in change gives you a lot more than just
 print-debugging.

 Stefan
 
 OK.
 
 How to use gdb? I am compiling the extension to a pyd file and
 importing it right now. So, I assume we need to, somehow load the
 extension dynamically for debugging? But how?

You write a testscript that exposes the error you want to observe in the
C-layer.

Then you do

$ gdb python
# set args testscript.py
# break some breakpoint, see how to enter that in gdb-docs
# run

That pretty much is it. You can't single-step python code this way, but you
can walk through C/C++-code.

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


Re: Python C/API simple debugging

2008-11-26 Thread k3xji
On Nov 26, 1:43 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 k3xji wrote:
  On Nov 26, 1:34 pm, Stefan Behnel [EMAIL PROTECTED] wrote:
  k3xji wrote:
   I am new to Python C API and finding it difficult to debug C
   extensions. So, basically I want to see the value of an integer value
   during the C API. Here is the code:

   #define LAST_MIX_VAL 0xDEADBEEF

   static PyObject *
   chash(PyObject *self, PyObject *args)
   {
   unsigned int key,result; //treat key like an usinged int.
   unsigned char a,b,c,d;

   key = result = 0;
   if (!PyArg_ParseTuple(args, i, key))
   return NULL;

   printf(Key:%i\n,Py_BuildValue(i, key));
   .
   .
   [...]
   - What is the preffered approach for these kind simple-debugging
   issue?

  If you want to simplify this kind of debugging as well as the general
  code writing itself, consider using Cython.

 http://cython.org/

  Apart from that, I'd use gdb for debugging these things. It does have a
  learning curve, but in change gives you a lot more than just
  print-debugging.

  Stefan

  OK.

  How to use gdb? I am compiling the extension to a pyd file and
  importing it right now. So, I assume we need to, somehow load the
  extension dynamically for debugging? But how?

 You write a testscript that exposes the error you want to observe in the
 C-layer.

 Then you do

 $ gdb python
 # set args testscript.py
 # break some breakpoint, see how to enter that in gdb-docs
 # run

 That pretty much is it. You can't single-step python code this way, but you
 can walk through C/C++-code.

 Diez

OK I see your point, I just expected an another way to do that from
distutils itself. Thanks for the answer.

By the way for simple print-debugging, below works right now, I forgot
to try that
fprintf(stderr,%d, key);

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


Re: Requesting direction for installation problem

2008-11-26 Thread Bruno Desthuilliers

Frederic Rentsch a écrit :

Hi,

Where can one get assistance if a Windows installation service fails to 
install an msi installer? I used to download zip files, but they seem to 
have been replaced with msi files. I know this issue is off topic here. 
So my question simply is: where is it not off topic?


I'd have a look at the comp.os.ms-windows* hierarchy...
--
http://mail.python.org/mailman/listinfo/python-list


[lambda]Is the behavior expected?

2008-11-26 Thread Alphones
Hi all,


def getFunc(x):
return lambda y : x + y

if __name__ == '__main__':
todo = []
proc = getFunc(1)
todo.append(lambda: proc(1))
proc = getFunc(2)
todo.append(lambda: proc(1))
proc = getFunc(3)
todo.append(lambda: proc(1))

todo.append(lambda: getFunc(1)(1))
todo.append(lambda: getFunc(2)(1))
todo.append(lambda: getFunc(3)(1))

for task in todo:
print task()

---
the program outputs:
4
4
4
2
3
4
in Python 2.6.
is that excpected?


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


Re: Tkinter and asyncronous socket

2008-11-26 Thread Steve Holden
[EMAIL PROTECTED] wrote:
 Hi all, I'm new to python and I've been spending the last week on GUI
 that refresh its content based on data periodically coming from a
 remote socket.
 I succeded in doing it (thanks newsgroups and online manual!) using
 the Tkinter.after method to implement a busy wait on the socket (which
 I had previously set to non blocking)
 I should be happy with it, but on windows (application must be multi-
 platform) the busy wait leads to a 100% CPU usage. I'm trying to
 implement it the other way round: a socket process that updates a
 label (or a queue object) in the GUI. I can't figure out how to do
 this. Anyone can post hints? With some details, maybe?
 
Processes are probably a bit heavyweight for this purpose: they create
difficulties in communication (unless you use the new multiprocessing
library in 2.6).

One approach would be to run the socket code in blocking mode in a
separate thread started by the (main program) GUI thread at program
startup, and communicating results back via a Queue.Queue or similar to
the GUI thread. That thread wakes itself up once every (say) 500 mS to
check for updates from the socket side.

You should see your CPU utilization go down then. The threading.thread
library is actually much easier to use than you would think, though it's
possible to get things wrong by assuming data sharing will work in ways
it actually doesn't. But if you have the main thread pass a Queue to the
networking thread, that should be a reliable means of communication.

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

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


Re: Multiple equates

2008-11-26 Thread Cameron Laird
In article [EMAIL PROTECTED],
Lawrence D'Oliveiro  [EMAIL PROTECTED] wrote:
Cameron Laird wrote:

 I've been trying to decide if there's any sober reason to advocate
 the one-liner
 
 map(lambda i: a.__setitem__(i, False), [x1, x2, x3, ..., x1024])

Are lambdas like the Dark Side of Python?

:)

Enough so, apparently, that I'm reluctant even to touch that question.
--
http://mail.python.org/mailman/listinfo/python-list


ONLINE EARNINGS $$$ 500 - $$$ 1000 PER MONTH WITHOUT INVESTMENT...

2008-11-26 Thread alan wells
ONLINE EARNINGS $$$ 500 - $$$ 1000 PER MONTH WITHOUT INVESTMENT...

projectpayday has been proven to a legit source of income that can be
earned the same day you sign up.the best programme i found in online
that it pays
more than $100 perday to me. they provides you step by step guide
untill than you made your first payment.You won't get rich but
1,000s of people have proven it's
a realistic extra income system for the Average Joe.. just have a
look at this network.when i just join here i start earn within 15
minutes

http://tinyurl.com/45twel

The best opportunity to earn money. It is a free money making network.
Mkke use it
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is the behavior expected?

2008-11-26 Thread bearophileHUGS
Alphones:
 it is a little deferent from other script language.

See also here:
http://en.wikipedia.org/wiki/Dynamic_scope#Dynamic_scoping

Python doesn't have such automatic closures, probably for performance
reasons and/or maybe to keep its C implementation simpler (maybe other
people here can give you an explanation of this, I too am curious).

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to get a directory file descriptor?

2008-11-26 Thread Nick Craig-Wood
Cong Ma [EMAIL PROTECTED] wrote:
  Thanks for your reply. I checked my Python 2.5 install on Linux and there's 
 the
  O_DIRECTORY flag. However this is not mentioned anywhere in the Library 
 Reference.
 
  There's another question regarding to this flag though: I checked the manual 
 of
  the Linux system call open(2), in which there's a paragraph on this flag:
 
 O_DIRECTORY
If pathname is not a directory, cause the open  to  fail.   
 This
flag is Linux-specific, and was added in kernel version 
 2.1.126,
to avoid denial-of-service problems if opendir(3) is called on 
 a
FIFO  or  tape  device,  but  should  not be used outside of 
 the
implementation of opendir(3).

That says avoid to me!

  Note the should not be used outside of the implementation of opendir(3) 
 part.
  Does that mean using Python's os.open() with the O_DIRECTORY flag is a Bad
  Thing?

IMHO yes.

 In C, I think, calling opendir() followed by dirfd() should be the
 correct way of doing this?

Here is how you do exactly that in python using ctypes

from ctypes import CDLL, c_char_p, c_int, Structure, POINTER
from ctypes.util import find_library

class c_dir(Structure):
Opaque type for directory entries, corresponds to struct DIR
c_dir_p = POINTER(c_dir)

c_lib = CDLL(find_library(c))
opendir = c_lib.opendir
opendir.argtypes = [c_char_p]
opendir.restype = c_dir_p
dirfd = c_lib.dirfd
dirfd.argtypes = [c_dir_p]
dirfd.restype = c_int
closedir = c_lib.closedir
closedir.argtypes = [c_dir_p]
closedir.restype = c_int

dir_p = opendir(.)
print dir_p = %r % dir_p
dir_fd = dirfd(dir_p)
print dir_fd = %r % dir_fd
print closed (rc %r) % closedir(dir_p)

Which prints on my linux machine

dir_p = ctypes.LP_c_dir object at 0xb7d13cd4
dir_fd = 3
closed (rc 0)

I don't know why os doesn't wrap - opendir, closedir, dirfd, readdir
etc - I guess because except if you are doing something esoteric, then
os.list and os.walk do everything you could possibly want.

-- 
Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting in to metaprogramming

2008-11-26 Thread Hendrik van Rooyen
Aaron Brady [EMAIL PROTECTED] wrote:


I don't know a clean, reliable way to structure a metaprogram though.
Mine always turn out messy.

Yes.

Then another thing - it strikes me that any problem that can be solved
by metaprogramming, can be solved by putting similar code into a class
and instanciating an instance.

Does anybody know if this is true?

If it is, it limits the usefulness of metaprogramming to the creation
of stored procedures for later execution.

- Hendrik



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


Re: what's so difficult about namespace?

2008-11-26 Thread Joshua Cranmer

Xah Lee wrote:

In many languages, they don't have namespace and is often a well known
sour point for the lang. For example, Scheme has this problem up till
R6RS last year. PHP didn't have namespace for the past decade till
about this year. Javascript, which i only have working expertise,
didn't have namespace as he mentioned in his blog. Elisp doesn't have
name space and it is a well known major issue.


Namespaces are useful for one reason: they allow you to have conflicts 
with names in some cases. In Java, there are two Lists: java.awt.List 
and java.util.List. Since a name must only be unique within a namespace, 
you can use shorter names without fear of conflict.


In languages without these namespaces, you end up with stuff like 
g_type_init, e_data_server_module_init, mysql_connect, etc., where the 
prefixes are used to emulate the unique nature of namespaces.



Of languages that do have namespace that i have at least working
expertise: Mathematica, Perl, Python, Java. Knowing these langs
sufficiently well, i do not see anything special about namespace.


Most features aren't sufficiently appreciated until one has to do 
without it. The avoidance of collision that comes with namespaces has 
shown to be sufficiently useful that I doubt we'll ever see a future 
major language that doesn't have some sort of namespace feature.


 The

_essence_ of namespace is that a char is choosen as a separator, and
the compiler just use this char to split/connect identifiers.


That's just composition of namespace names. It's not what namespaces is 
about.



i cannot fathom what could possibly be difficult of
introducing or implementing a namespace mechanism into a language.


Namespaces go to the very core of a language, name resolution. 
Retroactively adding such a feature is extremely difficult because there 
is a strong chance of accidentally breaking existing code.


 I

do not understand, why so many languages that lacks so much needed
namespace for so long? If it is a social problem, i don't imagine they
would last so long. It must be some technical issue?


It's technical: it would be difficult to retroactively implement such a 
feature.


--
Beware of bugs in the above code; I have only proved it correct, not 
tried it. -- Donald E. Knuth

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


Apache mod_python: I don't receive anything with POST method

2008-11-26 Thread tengounplanb
Hi,

I'm using a simple form to make possible the users of our site upload
files.

html
headmeta http-equiv=Content-Type content=text/html;
charset=iso-8859-1/head
body
form method=post enctype=multipart/form-data action=/ws/
upload.py/
input name=upfile type=file size=50/br
input type=submit value=send/
/form
/body
/html

The upload.py looks like this:

from mod_python import apache, util;

def index(req):
form = util.FieldStorage(req, keep_blank_values=1)
try:
# form is empty here
# return form -- I get {}
ufile = form.get('upfile', None)

if not form.has_key('upfile'):
return :( No 'upfile' key

# some checks. I never get beyond here

ufile = form['upfile']
if ufile.file:
return ufile.file.name
else:
return :( It's not a file
except Exception, e:
return 'Fail: ' + str(e)

I'm getting an empty 'form'. No 'upfile' key at all. I've tried to add
some other text fields but the result is the same: empty. If I use GET
method with text fields, it works properly.

Currently I'm using:
Apache 2.2.9 (initially I used Apache 2.2.3 too)
mod_python 3.3.1 (initially I used mod_python 3.2.10 too)
Python 2.5.2

Thanks

Best regards,
León
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using dictionary to hold regex patterns?

2008-11-26 Thread Bruno Desthuilliers

André a écrit :
(snip)

you don't need to use pattern.items()...

Here is something I use (straight cut-and-paste):

def parse_single_line(self, line):
'''Parses a given line to see if it match a known pattern'''
for name in self.patterns:
result = self.patterns[name].match(line)


FWIW, this is more expansive than iterating over (key, value) tuples 
using dict.items(), since you have one extra call to dict.__getitem__ 
per entry.



if result is not None:
return name, result.groups()
return None, line


where self.patterns is something like
self.patterns={
'pattern1': re.compile(...),
'pattern2': re.compile(...)
}

The one potential problem with the method as I wrote it is that
sometimes a more generic pattern gets matched first whereas a more
specific pattern may be desired.


As usual when order matters, the solution is to use a list of (name, 
whatever) tuples instead of a dict. You can still build a dict from this 
list when needed (the dict initializer accepts a list of (name, object) 
as argument).


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


Re: Reg Expression - Get position of

2008-11-26 Thread Chris Rebert
On Wed, Nov 26, 2008 at 1:48 AM, M_H [EMAIL PROTECTED] wrote:
 On Nov 25, 11:06 pm, r [EMAIL PROTECTED] wrote:
 On Nov 25, 4:33 pm, Jorgen Grahn [EMAIL PROTECTED] wrote:



  On Tue, 25 Nov 2008 12:41:53 -0800 (PST), r [EMAIL PROTECTED] wrote:
   On Nov 25, 10:36 am, M_H [EMAIL PROTECTED] wrote:
   Hey,

   I need the position of the last char 

   Let's say I have a string
   mystr =  mimetype=text/htmlcontent![CDATA[

   I need the posistion of the  (second sign) - so I can cut away the
   first part.

   The problem is that it can be like  but also like   or  

   But it is def the quotes and the closing brakets.

   How do I get the position of the   

   Hope you can help,
   Bacco

   why not just spilt

   mystr =  'mimetype=text/htmlcontent![CDATA['
   mystr.split('', 2)[-1]
   '![CDATA['

   you don't want to use an re for something like this

  Depends on if you have an irrational fear of REs or not ... I agree
  that REs are overused for things which are better done with split, but
  in this case I think an RE would be clearer.

   re.sub('.*', '', 'dkjkdjdd')

  'dd'

  -- assuming he means what I think he means. The question was almost
  impossible to comprehend.

  /Jorgen

  --
// Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu
  \X/ snipabacken.se  R'lyeh wgah'nagl fhtagn!

 i think what M_H wanted was to find the second occurance of  char
 in  mystr.
 Now if mystr will always look exactly as show then Jorgen Grahn's re
 will work fine. But it looks to me that the poster only showed us a
 portion of the string, and as you can see the mimetype tag is not
 closed in mystr, which would break your re, if the string acually
 extends further. Split would be fool-proof in all situations. But then
 again i had to read the post 5 times before i understood it. It may be
 advisable for M_H to repost the question in a clearer manner so that
 we can be sure our answers are correct!


 Thanks for all your answers.
 R is correct with his assumptions - sorry for the confusion.

 So let me post it again, easier

 I have a beginning of a (longer) string who is like:
 mystr =  'mimetype=text/htmlcontent![CDATA['
 or like
 mystr =  'mimetype=text/html content![CDATA['
 or like
 mystr =  'mimetype=text/html 
  NewLine content![CDATA['

 I want to have the end-position of the mimetype tag (position as
 mystr.find('') returns, so I can use the number for a loop)
 However, I can't use just the '' because the character  could also
 be in the string of mimetype (I know, actually not in mimetype, but
 let's assume it).
 So that is why the filter shall be bulletproof and check for '' -
 with possible spaces between both characters.

 I don't know yet how to solve this issue - any recommendations?

Any particular reason you're not using an HTML parser (e.g. BeautifulSoup) ?

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

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

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


Re: Is the behavior expected?

2008-11-26 Thread Alphones
On 11月26日, 下午8时48分, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 Alphones wrote:
  Hi all,

  def getFunc(x):
  return lambda y : x + y

  if __name__ == '__main__':
  todo = []
  proc = getFunc(1)
  todo.append(lambda: proc(1))
  proc = getFunc(2)
  todo.append(lambda: proc(1))
  proc = getFunc(3)
  todo.append(lambda: proc(1))

  todo.append(lambda: getFunc(1)(1))
  todo.append(lambda: getFunc(2)(1))
  todo.append(lambda: getFunc(3)(1))

  for task in todo:
  print task()

  ---
  the program outputs:
  4
  4
  4
  2
  3
  4
  in Python 2.6.
  is that excpected?

 Yes. Creating a lambda will close over the current *names* in the scope,
 *not* their respective values. For that, you need to create a new scope -
 e.g. by bindig the value to a argument of the lambda:

 lambdas = []
 for i in xrange(10):
 lambda i=i : i ** 2

 for l in lambdas:
 l()

 Diez

thanks :D
now I know what's wrong with my program.
it is a little deferent from other script language.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Official definition of call-by-value (Re: Finding the instance reference...)

2008-11-26 Thread Antoon Pardon
On 2008-11-20, greg [EMAIL PROTECTED] wrote:
 Antoon Pardon wrote:

 You are changing your argument. In a follow up you
 made the point that call by value should be as it
 was intended by the writers of the algol 60 report.

 No, I was countering the argument that call by value
 is short for call by copying the value. I was pointing
 out that the inventors of the term didn't use any such
 words.

That doesn't counter that that was intended.

 Arguing that their words were intended to imply copying,
 as part of the essence of the idea, is making an even
 bigger assumption about their intentions, IMO.

In their document assignment was a copying.

IMO the bigger assumption is to assume that these people
wanted to define call by value for languages which
would have different assignment semantics than their
own.

 Rather it seems to me that the essence of the idea they
 had in mind is that call-by-value is equivalent to
 assignment.

In their particular context.

 Furthermore, I don't seem to be alone in coming to that
 conclusion -- the designers of other dynamic languages
 appear to be using the same logic when they describe
 their parameter passing as call-by-value.

So what. Some designers do and some don't and some
make a particular effort to do different.

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


Re: Security implications of using open() on untrusted strings.

2008-11-26 Thread Jorgen Grahn
On Tue, 25 Nov 2008 23:37:25 +0100, News123 [EMAIL PROTECTED] wrote:
 Jorgen Grahn wrote:
   Compare with a language (does Perl allow this?) where if the string
   is rm -rf /|, open will run rm -rf / and start reading its output.
   *That* interface would have been 

 Good example. (for perl):

I should actually have removed that paragraph from my posting.
I was about to write *That* interface would have been dangerous! but
then I thought Hm, isn't the user supposed to be in control of that
string, and isn't it his fault if he enters '-rm -rf |', just as if
he entered the name of his most valuable file?

I don't know ...

 The problem doesn't exist in python
 open(rm -rf / |) would try to open a file with exactly that name and
 it would fail if it doesn't exist.

 In perl the perl script author has the choice to be safe (three argument
 open) or to allow stupid or nice things with a two argument open.

...

 Sometimes I miss the 'dangerous variation' in python and I explicitely
 add code in python that the filename '-' will be treated as stdin for
 files to be read and as stdout for files to be written to

That's something I frequently do, too. And I see no harm in it, if I
document it and people expect it (for those who don't know, reserving
'-' for this is a Unix tradition).

/Jorgen

-- 
  // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.se  R'lyeh wgah'nagl fhtagn!
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to get a directory file descriptor?

2008-11-26 Thread Cong Ma
Nick Craig-Wood wrote:
 Here is how you do exactly that in python using ctypes
 
 from ctypes import CDLL, c_char_p, c_int, Structure, POINTER
 from ctypes.util import find_library
 
 class c_dir(Structure):
 Opaque type for directory entries, corresponds to struct DIR
 c_dir_p = POINTER(c_dir)
 
 c_lib = CDLL(find_library(c))
 opendir = c_lib.opendir
 opendir.argtypes = [c_char_p]
 opendir.restype = c_dir_p
 dirfd = c_lib.dirfd
 dirfd.argtypes = [c_dir_p]
 dirfd.restype = c_int
 closedir = c_lib.closedir
 closedir.argtypes = [c_dir_p]
 closedir.restype = c_int
 
 dir_p = opendir(.)
 print dir_p = %r % dir_p
 dir_fd = dirfd(dir_p)
 print dir_fd = %r % dir_fd
 print closed (rc %r) % closedir(dir_p)
 
 Which prints on my linux machine
 
 dir_p = ctypes.LP_c_dir object at 0xb7d13cd4
 dir_fd = 3
 closed (rc 0)
 
 I don't know why os doesn't wrap - opendir, closedir, dirfd, readdir
 etc - I guess because except if you are doing something esoteric, then
 os.list and os.walk do everything you could possibly want.
 

Thank you so much Nick. I'll take a look into the ctypes module.

I guess the reason of Python library not including those wrappers has something
to do with standard compliance. The fchdir(2) manual says comforming to
POSIX.1-2001 but the opendir(3) manual says fdopendir() is specified in
POSIX.1-2008.

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


Re: How to get a directory file descriptor?

2008-11-26 Thread alex23
On Nov 26, 11:07 pm, Steve Holden [EMAIL PROTECTED] wrote:
 alex23 wrote:
  I'm pretty certain it was present under Windows XP as well.

 Since these two are the exact same version I presume O_DIRECTORY is not
 meaningful on Windows. Anyway, when I try to use O_RDONLY on Vista I get
 Permission denied:

Sorry, my bad. I got the exact same Permission denied response when
I first tried this under XP, so I shelled to a linux box and tested
there...then promptly forgot all about it. In my defence, it was
pretty late at night when I did so :)

In fact, I can't even find a reference to O_DIRECTORY in the manual at
all...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Getting in to metaprogramming

2008-11-26 Thread Michele Simionato
On Nov 26, 11:55 pm, Hendrik van Rooyen [EMAIL PROTECTED]
wrote:
 Then another thing - it strikes me that any problem that can be solved
 by metaprogramming, can be solved by putting similar code into a class
 and instanciating an instance.

 Does anybody know if this is true?

 If it is, it limits the usefulness of metaprogramming to the creation
 of stored procedures for later execution.

 - Hendrik

Many times (probably most times) you can avoid code generation and use
classes or
higher order functions instead. Actually I don't like code generation
techniques
in Python and other languages. I would make an exception for Lisp-like
languages,
however, since there you a pretty powerful macro mechanism that in
some cases can be
better than using higher order functions, especially if performance is
important.
I say something more in the latest episode of my Adventures of a
Pythonista in Schemeland
which some of you may find interesting: 
http://www.artima.com/weblogs/viewpost.jsp?thread=240836


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


Re: confused about classes and tkinter object design

2008-11-26 Thread Bruno Desthuilliers

marc wyburn a écrit :

Hi,

I've created my first Tkinter GUI class which consists of some buttons
that trigger functions.  I have also created a
tkFileDialog.askdirectory control to local a root folder for log
files.

I have several file paths that depend on the value of
tkFileDialog.askdirectory should I create an object that inherits this
value or can I point functions at the GUI class?

I am creating the tkinter GUI instance using;

if __name__ == __main__:
GUI = AuditorGUI()


Note that at this point, the AuditorGUI class is not yet defined, so you 
should get a NameError.



GUI.mainloop()



class AuditorGUI(Frame):


I assume you have all necessary imports in your real code...


def __init__(self):
Frame.__init__(self)
self.pack(expand = YES, fill = BOTH)

##  Create GUI objects

self.currentdir = StringVar()
self.currentdir.set(os.getcwd())

self.logdir = Button(self, text=Choose Data
directory,command=self.choose_dir)
self.logdir.grid(row=1,column=0,sticky='nsew',pady=20,padx=20)

self.labeldirpath = Label(self, textvariable=self.currentdir)

def choose_dir(self):
dirname = tkFileDialog.askdirectory
(parent=self,initialdir=self.currentdir.get(),title='Please select a
directory')
if len(dirname )  0:
self.currentdir.set(dirname)

I think I have created an instance of the AuditorGUI class called GUI
so should be able to access the path using GUI.currentdir but this
doesn't work.


does not work is (almost) the less possible usefull description of a 
problem. What happens exactly ? Do you have a traceback ? If so, please 
post the full traceback and error message. Else, please explain what 
result you get. And if possible, post minimal *working* code reproducing 
the problem.



I'm still struggling with classes so not sure whether my problem is
tkinter related or not.


Minus the couple problems above (ie: trying to instanciate a 
non-yet-existing class, and lack of necessary imports), it seems correct 
- at least wrt/ class definition and instanciation.

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


Python C/API simple debugging

2008-11-26 Thread k3xji
Hi all,

I am new to Python C API and finding it difficult to debug C
extensions. So, basically I want to see the value of an integer value
during the C API. Here is the code:

#define LAST_MIX_VAL 0xDEADBEEF

static PyObject *
chash(PyObject *self, PyObject *args)
{
unsigned int key,result; //treat key like an usinged int.
unsigned char a,b,c,d;

key = result = 0;
if (!PyArg_ParseTuple(args, i, key))
return NULL;

printf(Key:%i\n,Py_BuildValue(i, key));
.
.

So, I just want to see the contents of local variable key. If I call
printf(..) without Py_BuildValue(), the interpreter shuts down, because
(I am assuming) printf is allocating some value in heap that is not in
the interpreter's heap itself which is causing the corruption.

This way it works, but this time I cannot see correct key content.

So, questions are:
- What I am doing wrong here?
- What is the preffered approach for these kind simple-debugging
issue? I searched C/API ref but cannot see any help on that?

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


Re: Python surpasses Perl in popularity?

2008-11-26 Thread Steve Holden
Roy Smith wrote:
 In article [EMAIL PROTECTED],
  Jorgen Grahn [EMAIL PROTECTED] wrote:
  
 Hard to take a popularity index seriously when Logo is at #19 and
 Bourne shell at #32 ... and then they suggest that their readers can
 use it to make a strategic decision about what programming language
 should be adopted when starting to build a new software system.
 
 When you've seen some of the shell scripts I've seen, it's not hard to 
 imagine that logo might be a better choice of programming language.

:)

In fact all that's really happened is that Perl has slid down the ranks,
at least temporarily. Python has been around the 6/7 mark for a while now.

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

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


Re: Reg Expression - Get position of

2008-11-26 Thread M_H
On Nov 25, 11:06 pm, r [EMAIL PROTECTED] wrote:
 On Nov 25, 4:33 pm, Jorgen Grahn [EMAIL PROTECTED] wrote:



  On Tue, 25 Nov 2008 12:41:53 -0800 (PST), r [EMAIL PROTECTED] wrote:
   On Nov 25, 10:36 am, M_H [EMAIL PROTECTED] wrote:
   Hey,

   I need the position of the last char 

   Let's say I have a string
   mystr =  mimetype=text/htmlcontent![CDATA[

   I need the posistion of the  (second sign) - so I can cut away the
   first part.

   The problem is that it can be like  but also like   or      

   But it is def the quotes and the closing brakets.

   How do I get the position of the   

   Hope you can help,
   Bacco

   why not just spilt

   mystr =  'mimetype=text/htmlcontent![CDATA['
   mystr.split('', 2)[-1]
   '![CDATA['

   you don't want to use an re for something like this

  Depends on if you have an irrational fear of REs or not ... I agree
  that REs are overused for things which are better done with split, but
  in this case I think an RE would be clearer.

   re.sub('.*', '', 'dkjkdjdd')

  'dd'

  -- assuming he means what I think he means. The question was almost
  impossible to comprehend.

  /Jorgen

  --
    // Jorgen Grahn grahn@        Ph'nglui mglw'nafh Cthulhu
  \X/     snipabacken.se          R'lyeh wgah'nagl fhtagn!

 i think what M_H wanted was to find the second occurance of  char
 in  mystr.
 Now if mystr will always look exactly as show then Jorgen Grahn's re
 will work fine. But it looks to me that the poster only showed us a
 portion of the string, and as you can see the mimetype tag is not
 closed in mystr, which would break your re, if the string acually
 extends further. Split would be fool-proof in all situations. But then
 again i had to read the post 5 times before i understood it. It may be
 advisable for M_H to repost the question in a clearer manner so that
 we can be sure our answers are correct!


Thanks for all your answers.
R is correct with his assumptions - sorry for the confusion.

So let me post it again, easier

I have a beginning of a (longer) string who is like:
mystr =  'mimetype=text/htmlcontent![CDATA['
or like
mystr =  'mimetype=text/html content![CDATA['
or like
mystr =  'mimetype=text/html 
  NewLine content![CDATA['

I want to have the end-position of the mimetype tag (position as
mystr.find('') returns, so I can use the number for a loop)
However, I can't use just the '' because the character  could also
be in the string of mimetype (I know, actually not in mimetype, but
let's assume it).
So that is why the filter shall be bulletproof and check for '' -
with possible spaces between both characters.

I don't know yet how to solve this issue - any recommendations?
--
http://mail.python.org/mailman/listinfo/python-list


Re: what's so difficult about namespace?

2008-11-26 Thread Xah Lee
On Nov 26, 5:45 am, Joshua Cranmer [EMAIL PROTECTED] wrote:
  i cannot fathom what could possibly be difficult of
  introducing or implementing a namespace mechanism into a language.

 Namespaces go to the very core of a language, name resolution.
 Retroactively adding such a feature is extremely difficult because there
 is a strong chance of accidentally breaking existing code.

could you give some technical detail on this?

i don't know compiler so am probably being foolish here... but i
suppose ultimately name resolution and storage at heart is something
like a hashtable...  namely,

put ‹identifier 1› table
put ‹identifier 2› table

and lookup is just

retrieve ‹identifier› table

and now suppose we introduced namespace, so i imagine the compiler
simply just concat namespace component befor put, and split before
retrieve?

  Xah
∑ http://xahlee.org/

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


Re: zope vs openACS

2008-11-26 Thread Stefan Scholl
Bruno Desthuilliers [EMAIL PROTECTED] wrote:
 Stefan Scholl a écrit :
 [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 On Nov 19, 1:50 am, gavino [EMAIL PROTECTED] wrote:
 what is nicer about each?
 Yes.
 
 And No.
 
 Or maybe ?

This isn't Haskell.

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


Re: How to get a directory file descriptor?

2008-11-26 Thread Steve Holden
alex23 wrote:
 On Nov 26, 3:26 pm, greg [EMAIL PROTECTED] wrote:
 os.O_DIRECTORY must be fairly new -- it doesn't exist
 in my 2.5 installation. But os.O_RDONLY seems to work
 just as well for this purpose.
 
 Which OS are you using?
 
 Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
 [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
 Type help, copyright, credits or license for more information.
 import os
 hasattr(os, 'O_DIRECTORY')
 True
 
 I'm pretty certain it was present under Windows XP as well.
 

OK, here's a little mystery. This is Vista (spit):

Microsoft Windows [Version 6.0.6001]
Copyright (c) 2006 Microsoft Corporation.  All rights reserved.

C:\Users\sholdenpython
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
(Intel)] on win32
Type help, copyright, credits or license for more information.
 import os
 f = os.open(., os.O_DIRECTORY)
Traceback (most recent call last):
  File stdin, line 1, in module
AttributeError: 'module' object has no attribute 'O_DIRECTORY'
 hasattr(os, 'O_DIRECTORY')
False


Since these two are the exact same version I presume O_DIRECTORY is not
meaningful on Windows. Anyway, when I try to use O_RDONLY on Vista I get
Permission denied:

 f = os.open(os.path.abspath(Documents), os.O_RDONLY)
Traceback (most recent call last):
  File stdin, line 1, in module
OSError: [Errno 13] Permission denied: 'C:\\Users\\sholden\\Documents'

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

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


Re: Python/C API: using from a shared library

2008-11-26 Thread Robie Basak
On 2008-11-25, Robie Basak [EMAIL PROTECTED] wrote:
 If I use dlopen() to open a shared library that I've written, and that
 shared library tries to use the Python/C API, then it fails. I've
 reduced the problem to the test case below. The error is:

 ImportError: /usr/lib/python2.5/lib-dynload/time.so: undefined symbol:
 PyExc_ValueError

I've submitted a bug for this. See http://bugs.python.org/issue4434 for
an more detailed explanation and a workaround.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python C/API simple debugging

2008-11-26 Thread Philip Semanchuk


On Nov 26, 2008, at 6:47 AM, k3xji wrote:

By the way for simple print-debugging, below works right now, I  
forgot

to try that
fprintf(stderr,%d, key);



As a new extension developer myself, I'll pass along the following  
handy macro that I swiped from another extension (psycopg I think):


#ifdef DEBUG_ON
#define DPRINTF(fmt, args...) fprintf(stderr, +++  fmt, ## args)
#else
#define DPRINTF(fmt, args...)
#endif

You can use it in code like so:

DPRINTF(key == %d\n, key);


And then turn all of your debug statements on/off by recompiling with/ 
without the DEBUG_ON flag.



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


Re: Python surpasses Perl in popularity?

2008-11-26 Thread Marco Mariani

Steve Holden wrote:


In fact all that's really happened is that Perl has slid down the ranks,
at least temporarily. Python has been around the 6/7 mark for a while now.


Also.. can someone attempt to explain the funny correlation in 
popularity over time between, for instance, Python and Delphi? :-)


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


How to use Py_DEBUG ?

2008-11-26 Thread MCG
Hello,

Does somebody know how to debug this kind of bug ? (see following
traceback)
I suppose that the bug is in my program (executable with python
embedded) and not in python... but how to locate it ?
I tried to compile all C sources calling Python.h with -DPy_DEBUG and
to link my code against config_d/libpython2.5.a, but I get no more
information.
Is it the right way ?

Can gc module get interesting information ?


#0  0x093179a9 in visit_decref (op=0x302e3020, data=0x0) at ../Modules/
gcmodule.c:270
#1  0x0928c4c1 in dict_traverse (op=0xa315214, visit=0x9317976
visit_decref,
arg=0x0) at ../Objects/dictobject.c:1892
#2  0x09317a74 in subtract_refs (containers=0x96802c8) at ../Modules/
gcmodule.c:295
#3  0x09318746 in collect (generation=2) at ../Modules/gcmodule.c:790
#4  0x09319245 in PyGC_Collect () at ../Modules/gcmodule.c:1265
#5  0x0930857a in Py_Finalize () at ../Python/pythonrun.c:389
#6  0x0930b5ef in Py_Exit (sts=0) at ../Python/pythonrun.c:1618
#7  0x09309caf in handle_system_exit () at ../Python/pythonrun.c:1054
#8  0x09309ccd in PyErr_PrintEx (set_sys_last_vars=1) at ../Python/
pythonrun.c:1064
#9  0x093099df in PyErr_Print () at ../Python/pythonrun.c:978
#10 0x0930944e in PyRun_SimpleFileExFlags (fp=0x9ce6900,
filename=0xbf840644 Python/Execution/E_SUPERV.py, closeit=1,
flags=0xbf83fbb0)
at ../Python/pythonrun.c:883
#11 0x09308b7c in PyRun_AnyFileExFlags (fp=0x9ce6900,
filename=0xbf840644 Python/Execution/E_SUPERV.py, closeit=1,
flags=0xbf83fbb0)
at ../Python/pythonrun.c:698
#12 0x09317648 in Py_Main (argc=23, argv=0xbf83fcc4) at ../Modules/
main.c:523
#13 0x0809eaa9 in main (argc=23, argv=0xbf83fcc4)

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


Re: Getting in to metaprogramming

2008-11-26 Thread Steven D'Aprano
On Thu, 27 Nov 2008 00:55:33 +0200, Hendrik van Rooyen wrote:

 Aaron Brady [EMAIL PROTECTED] wrote:
 
 
I don't know a clean, reliable way to structure a metaprogram though.
Mine always turn out messy.
 
 Yes.
 
 Then another thing - it strikes me that any problem that can be solved
 by metaprogramming, can be solved by putting similar code into a class
 and instanciating an instance.
 
 Does anybody know if this is true?

Well, I don't know about any problem. And it's not so much about 
whether metaprograms can solve problems that can't be solved by anything 
else, as whether metaprograms can solve problems more effectively than 
other techniques.

If you include factory functions, class factories, the builder design 
pattern, metaclasses, etc. as metaprogramming, then I use it all the 
time, and find it an excellent technique to use.

But if you mean using a Python program to generate Python source code, 
then I can't think of any time I used it. Which doesn't mean that others 
don't find it helpful, only that I haven't yet.

Thinking further back, when I was young and programming in Apple's 
Hypercard 4GL, I used to frequently use Hypercard scripts to generate new 
Hypercard scripts. That was to work around the limitations of the 
scripting language.

I don't think metaprogramming in the limited sense (programs to output 
source code) is a bad idea, but I do think that there are probably better 
alternatives in a language like Python.


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


Re: Is the behavior expected?

2008-11-26 Thread Alphones
On 11月26日, 下午9时28分, [EMAIL PROTECTED] wrote:
 Alphones:

  it is a little deferent from other script language.

 See also here:http://en.wikipedia.org/wiki/Dynamic_scope#Dynamic_scoping

 Python doesn't have such automatic closures, probably for performance
 reasons and/or maybe to keep its C implementation simpler (maybe other
 people here can give you an explanation of this, I too am curious).

 Bye,
 bearophile

i encountered this problem when i'm writing a program for packaging
files.
the program generates tasks according to description file.
and tasks are deferent from each other, and should be excuted at the
last of program.

i have experience on Lua and have learned about scheme and haskell, so
i wrote the wrong code in python.

now my solution is, using class taskCreator to create tasks and put
them into tasklist.
class taskCreator:
def __init__(self, proc, input, output):
self.proc = proc
self.input = input
self.output = output
def call(self):
return self.proc.call(self.input, self.output)
'proc' is generated by procCreators, it's specified.

it looks more complex than lambda one.

is there any other simple way to implement it?
and does the taskCreator mean 'create a new scope'?

Suggestions will be appreciated. Thanks.

PS: i'm a newbie in Python (started from today)

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


Re: How to get a directory file descriptor?

2008-11-26 Thread alex23
On Nov 26, 8:56 pm, Cong Ma [EMAIL PROTECTED] wrote:
 Thanks for your reply. I checked my Python 2.5 install on Linux and there's 
 the
 O_DIRECTORY flag. However this is not mentioned anywhere in the Library 
 Reference.

Yes, I just noticed that myself.

        O_DIRECTORY
               If pathname is not a directory, cause the open  to  fail.   This
               flag is Linux-specific, and was added in kernel version 2.1.126,

Well, that certainly explains it's absence :)

 Note the should not be used outside of the implementation of opendir(3) 
 part.
 Does that mean using Python's os.open() with the O_DIRECTORY flag is a Bad
 Thing?

I'm sorry, that's outside of my knowledge. But it seemed to work fine
when I tried it.

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


Re: what's so difficult about namespace?

2008-11-26 Thread Lew

Xah Lee wrote:

Of languages that do have namespace that i [sic] have at least working
expertise: Mathematica, Perl, Python, Java. Knowing these langs
sufficiently well, i [sic] do not see anything special about namespace. The
_essence_ of namespace is that a char is choosen as a separator, and
the compiler just use this char to split/connect identifiers.


That is hardly the essence of namespaces, just a notational convenience to 
help humans relate to namespaces.  The essence of namespaces is that they are 
distinct.


It's also not an accurate statement.  XML namespaces, for example, use many 
characters as separators, not just one, but that's not the essence.  The 
essence is that all the characters matter, not just the putative separators.



Although i [sic] have close to zero knowledge about compiler or parser, but
from a math point of view and my own 18 years of programing
experience, i [sic] cannot fathom what could possibly be difficult of
introducing or implementing a namespace mechanism into a language. I
do not understand, why so many languages that lacks so much needed


Point not proven.  If they were really needed in every language, every 
language would have them.



namespace for so long? If it is a social problem, i [sic] don't imagine they
would last so long. It must be some technical issue?


Yeah, like technically they aren't needed everywhere.


Could any compiler expert give some explanation?


Compilers are not relevant.  XML has namespaces, and compilers certainly 
aren't the issue there.


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


Re: Getting in to metaprogramming

2008-11-26 Thread Kay Schluehr
On 25 Nov., 11:08, Rafe [EMAIL PROTECTED] wrote:
 Hi,

 In the name of self-education can anyone share some pointers, links,
 modules, etc that I might use to begin learning how to do some
 metaprogramming. That is, using code to write code (right?)

 Cheers,

 - Rafe

http://www.letmegooglethatforyou.com/?q=python+metaprogramming
--
http://mail.python.org/mailman/listinfo/python-list


Re: [lambda]Is the behavior expected?

2008-11-26 Thread Diez B. Roggisch
Alphones wrote:

 Hi all,
 
 
 def getFunc(x):
 return lambda y : x + y
 
 if __name__ == '__main__':
 todo = []
 proc = getFunc(1)
 todo.append(lambda: proc(1))
 proc = getFunc(2)
 todo.append(lambda: proc(1))
 proc = getFunc(3)
 todo.append(lambda: proc(1))
 
 todo.append(lambda: getFunc(1)(1))
 todo.append(lambda: getFunc(2)(1))
 todo.append(lambda: getFunc(3)(1))
 
 for task in todo:
 print task()
 
 ---
 the program outputs:
 4
 4
 4
 2
 3
 4
 in Python 2.6.
 is that excpected?

Yes. Creating a lambda will close over the current *names* in the scope,
*not* their respective values. For that, you need to create a new scope -
e.g. by bindig the value to a argument of the lambda:

lambdas = []
for i in xrange(10):
lambda i=i : i ** 2

for l in lambdas:
l()

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


Re: Pyhon (with wxPython) on Windows' cygwin: can it be done fully ?

2008-11-26 Thread Steve Holden
Barak, Ron wrote:
 Hi Pythonistas,
 
 I read diaz's comments with interest, but - in my current configuration, I'm 
 unable to use pdb.
 
 I'm developing on cygwin and use wxPython.
 Consequently, I cannot use native cygwin Python, but my Python is actually 
 the Windows XP Python (i.e.,  /cygdrive/c/Python25/python.exe).
 This means that pdb (and, for that matter any Python shell (like IDLE)) gets 
 stuck upon invocation.
 
 I was wandering: is anybody able to use native Python on cygwin, or 
 alternately, to use Windows Python under cygwin in IDLE/pdb ?
 
That's a pretty crazy combination, which is more or less guaranteed to
cause problems. If you are using the standard Windows Python under
cygwin you will find it gives you issues with filenames, for example.
You won't be able to access them using the Cygwin names, so why not just
run the standard Windows Python under the Windows command line?

You can, of course, continue to use Cygwin for editing and command-line
Python. But you seem to be asking for trouble unnecessarily by running
Windows Python under Cygwin.

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

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


Re: Python surpasses Perl in popularity?

2008-11-26 Thread Roy Smith
In article [EMAIL PROTECTED],
 Marco Mariani [EMAIL PROTECTED] wrote:

 Steve Holden wrote:
 
  In fact all that's really happened is that Perl has slid down the ranks,
  at least temporarily. Python has been around the 6/7 mark for a while now.
 
 Also.. can someone attempt to explain the funny correlation in 
 popularity over time between, for instance, Python and Delphi? :-)

It's explained in http://en.wikipedia.org/wiki/Delphi.
--
http://mail.python.org/mailman/listinfo/python-list


Re: what's so difficult about namespace?

2008-11-26 Thread Steve Holden
Xah Lee wrote:
 On Nov 26, 5:45 am, Joshua Cranmer [EMAIL PROTECTED] wrote:
 i cannot fathom what could possibly be difficult of
 introducing or implementing a namespace mechanism into a language.
 Namespaces go to the very core of a language, name resolution.
 Retroactively adding such a feature is extremely difficult because there
 is a strong chance of accidentally breaking existing code.
 
 could you give some technical detail on this?
 
 i don't know compiler so am probably being foolish here... but i
 suppose ultimately name resolution and storage at heart is something
 like a hashtable...  namely,
 
 put ‹identifier 1› table
 put ‹identifier 2› table
 
 and lookup is just
 
 retrieve ‹identifier› table
 
 and now suppose we introduced namespace, so i imagine the compiler
 simply just concat namespace component befor put, and split before
 retrieve?
 
And therein lies the danger of imagination.

Typically the namespace components are looked up one by one, so for

   this.that.theother

first this will be looked up and (hopefully) yield an object with a
namespace, which will then be searched for that, yielding another
object with a namespace in which theother can be looked up. That's
certainly how it works in Python:

 import os
 dir(os)
[... , 'path', ...]
 dir(os.path)
[... , 'walk']
module 'os' from '/usr/lib/python2.4/os.pyc'
 os.path
module 'posixpath' from '/usr/lib/python2.4/posixpath.pyc'
 os.path.walk
function walk at 0xb7c4995c


Using a single global namespace table might work, but only for some
horrendously convoluted values of work.  To delete os.path you would
have to delete not only the key os.path but also all keys beginning
with os,path. -- it's the kind of solution a PHP programmer might have
dreamed up.

And before anyone bothers to point it out, yes, I know PHO now (finally)
has namespaces.

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

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


Re: Is the behavior expected?

2008-11-26 Thread Diez B. Roggisch
Alphones wrote:

 On 11月26日, 下午9时28分, [EMAIL PROTECTED] wrote:
 Alphones:

  it is a little deferent from other script language.

 See also here:http://en.wikipedia.org/wiki/Dynamic_scope#Dynamic_scoping

 Python doesn't have such automatic closures, probably for performance
 reasons and/or maybe to keep its C implementation simpler (maybe other
 people here can give you an explanation of this, I too am curious).

 Bye,
 bearophile
 
 i encountered this problem when i'm writing a program for packaging
 files.
 the program generates tasks according to description file.
 and tasks are deferent from each other, and should be excuted at the
 last of program.
 
 i have experience on Lua and have learned about scheme and haskell, so
 i wrote the wrong code in python.
 
 now my solution is, using class taskCreator to create tasks and put
 them into tasklist.
 class taskCreator:
 def __init__(self, proc, input, output):
 self.proc = proc
 self.input = input
 self.output = output
 def call(self):
 return self.proc.call(self.input, self.output)
 'proc' is generated by procCreators, it's specified.
 
 it looks more complex than lambda one.
 
 is there any other simple way to implement it?
 and does the taskCreator mean 'create a new scope'?

Not exactly, but there is a saying:

Closures are a poor man's objects. And objects are a poor man's closures.

What you did creating a class and instantiating was to capture the
parameters you needed at a time, and using them within call at another
time.

A similar thing happens when you create a lambda with arguments assigned, as
I showed you - as then as part of the closure of the lambda there are the
names in it's parameter list, assigned to the values the right hand sides
had at the time being.

Depending on what you want to do, both approaches - classes or closures -
are valid. The more complex a problem gets, the more explicit  powerful a
class becomes, where it might be a bit of an overhead for really simple
problems.

One thing for example classes allow - which is interesting for you - is that
it is easy to look into them, for debugging/tracing. You can take a
taskCreator (BTW, read PEP 8 about naming conventions in python) and see
what is in there, e.g. logging it before executing the task or some such.

OTOH, a lambda (or function) is an opaque thing you can't ask such things,
making life a bit harder sometimes.

Diez


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


Re: Enumerating k-segmentations of a sequence

2008-11-26 Thread bullockbefriending bard
On Nov 26, 12:15 am, [EMAIL PROTECTED] wrote:
 bullockbefriending bard napisa³(a):



  I'm not sure if my terminology is precise enough, but what I want to
  do is:

  Given an ordered sequence of n items, enumerate all its possible k-
  segmentations.

  This is *not* the same as enumerating the k set partitions of the n
  items because I am only interested in those set partitions which
  preserve the order of the items. i.e. if the input sequence is (1 2 3
  4 5), then ((1 4) (2 3) (5)) is unacceptable, whereas ((1 2) (3) (4
  5)) is acceptable. Hence use of term 'segmentations'.

  e.g., for input sequence (1 2 3 4 5) and k = 3, I need a function
  which enumerates the following 3-segmentations:

  ((1 2 3) (4) (5))
  ((1 2) (3 4) (5))
  ((1 2) (3) (4 5))
  ((1) (2 3 4) (5))
  ((1) (2 3) (4 5))
  ((1) (2) (3 4 5))

  The reason I want to do this is to use it in some simple one-
  dimensional clustering, i.e. each set item (won't be just integers as
  above) will have a value of interest, and i'll select the particular
  set partition which minimises Sigma SSD (sum of squared differences
  from mean) of these values.

  It seems overkill to generate the full list of set partitions
  [including e.g. ((1 4) (2) (3 5))] because I intend to begin by
  sorting the input sequence such that element 1  element 2  ... 
  element n.

  Structural Recursion not being my strong point, any ideas on how to go
  about this would be much appreciated!

 I'm not sure if I correctly understood the semantics of what you need.
 Anyway it looks like a nice exercise in nested generators:

 def segmentations(sequence, k):
         assert 1 = k = len(sequence)
         if k == 1:
                 yield [sequence]
         else:
                 for headlen in xrange(1, len(sequence) - k + 2):
                         head, tail = sequence[:headlen], sequence[headlen:]
                         for tail_seg in segmentations(tail, k - 1):
                                 yield [head] + tail_seg

 for segmentation in segmentations((1, 2, 3, 4, 5), 3):
         print segmentation

 Regards,
 Marek

Exactly what I needed. Thank you all for examples and also for
explaining how to think about problems of this nature!

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


Re: How to get a directory file descriptor?

2008-11-26 Thread Terry Reedy

Steve Holden wrote:


import os
hasattr(os, 'O_DIRECTORY')

True

I'm pretty certain it was present under Windows XP as well.



f = os.open(., os.O_DIRECTORY)

Traceback (most recent call last):
  File stdin, line 1, in module
AttributeError: 'module' object has no attribute 'O_DIRECTORY'


The 3.0 manual lists 4 groups of flags: unix and windows, unix only, 
windows only, gnu only (check system-specific manual).  O_DIRECTORY  is 
in the gnu group.


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


Re: Python surpasses Perl in popularity?

2008-11-26 Thread Xah Lee
On Nov 25, 2:47 pm, Jorgen Grahn [EMAIL PROTECTED] wrote:
 On Mon, 24 Nov 2008 20:25:51 -0500, [EMAIL PROTECTED] [EMAIL PROTECTED] 
 wrote:
  QuotingXahLee[EMAIL PROTECTED]:

  herald: Python surpasses Perl in popularity!

  According to
  ?TIOBE Programming Community Index for November 2008? at
 http://www.tiobe.com/content/paperinfo/tpci/index.html

  it seems that Python has surpassed Perl in popularity this month!
  Interesting topic !

 Hard to take a popularity index seriously when Logo is at #19 and
 Bourne shell at #32 ... and then they suggest that their readers can
 use it to make a strategic decision about what programming language
 should be adopted when starting to build a new software system.

your remark is a bit overzealous. After all, we all know that site is
websearh based. Although it not some kinda scientific report, but it
does give some good indication of language popularity, however you
define that.

it is conceivable that logo is somewhat used more than bourne shell.

first of all, Logo is a lisp dialect. (it's one of the rare lisp sans
the parens.) The most famous logo book is the triology titled
something like Computer Science Logo Style, by Brian Harvey, who
teaches at UC Berkeley and now and then still post to
“comp.lang.scheme”.  (who, like some many veteran Scheme Lisp
dignitaries, cries out against the utter fuckup Scheme 6 (aka R6RS))

Bourne Shell, is pretty much replaced by Bash since several years ago.
For example, as far as i know, linuxes today don't have Bourne Shell
anymore. “sh” is just a alias to bash with some compatibility
parameter. That immediately wipe out a huge sector of unixes that
lives on Bourne Shell. This is a good thing. In about 2000 i called
for this. The fucking asshole Sun Microsystems insists on installing
at least 3 versions of shell utilities in several directories... (and
the BSD unixes insist on their inferior stupid versions of shell
tools)

To be sure, Logo is very much a academic lang, mostly for teaching and
for younsters. Much of its code is about drawing graphics. Some other
major use of Logo is in robotics, much associated with the Lego
robotics toys.

While Bourne Shell, as far as i can venture a guess, is still the
primary startup scripts in various unixes.

It is hard to put down exactly which is “popular”. We have to first
define what we mean by popular, of course. Is it number of programers/
users? Popularity in the sense of awareness? Number of software using
them out there? etc.

However, as mentioned before, all things considered, it is conceivable
that Logo is more popular than sh. For one thing, for any use of shell
script other than the machine startup scripts, people don't use bourne
shell anymore. They use bash, maybe tcsh, and probably vast majority
of unix/server shell oriented installation scripts are done in Perl or
python today.

For those interested in languages, see:

• Proliferation of Computing Languages
  http://xahlee.org/UnixResource_dir/writ/new_langs.html

It would be fruitful to actually set aside some 3 hours in some
weekend, to read thru these and the Wikipedia articles linked. You'll
get a survey of today's languages, what they are, what they do, their
nature, their field, and where the landscape of languages might be
tomorrow.

plain text version follows.
---

 Back to Computing and Its People.
Proliferation of Computing Languages

Xah Lee, 2008-07, 2008-11

There is a proliferation of computer languages today like never
before. In this page, i list some of them.

In the following, i try to list some of the langs that are created
after 2000, or become very active after 2000.

Functional langs:

Erlang↗. Functional, concurrent. Mostly used in a telecomunication
industry for corcurrency and continuous up-time features.
Haskell↗ Oldish, classic functional lang.
Mercury↗. Logic, functional.
Q↗. Functional lang, based on term rewriting. To be replaced by Pure↗.
Oz↗. Concurrent. Multiparadigm.
ML Family:

OCaml↗
Alice↗. Concurrent, ML derivative. Saarland University, Germany.
F#↗. Microsoft's functional lang.
Lisp family or similar:

Mathematica↗. Computer algebra system background. Used mostly for math
and research.
NewLisp↗. Lisp scripting style.
Arc↗. Paul Graham squeezing juice out of his celebrity status.
Qi↗. Common Lisp added with modern functional lang features.
Clojure↗. A new lisp dialect on Java platform.
Scheme↗, notably PLT Scheme↗. Used mostly for teaching.
(Dead. Dylan↗. Apple's re-invention of lisp for industrial programers,
active in the 1990s.)
Computer Algebra and Proof systems:

Coq↗. For formal proofs.
For much more, see Category:Computer algebra systems↗ and Automated
theorem proving↗.
Perl Family or derivative:

PHP↗. Perl derivative for server side web apps. One of the top 10 used
langs post 2000.
Ruby↗. Perl with rectified syntax and semantics.
Perl6↗. Next gen of perl.
Sleep↗. A scripting lang, perl syntax. On Java platform.
On Java Virtual Machine:

Scala↗. 

Re: what's so difficult about namespace?

2008-11-26 Thread Wojtek

Xah Lee wrote :

i cannot fathom what could possibly be difficult of
introducing or implementing a namespace mechanism into a language. I
do not understand, why so many languages that lacks so much needed
namespace for so long? If it is a social problem, i don't imagine they
would last so long. It must be some technical issue?


Simply put:
- it was not in the original language specification
- some hundreds of millions of distributed browsers interpret 
Javascript without namespaces
- to introduce namespaces into the language would require every browser 
to be replaced (at least if the user comes across a site which uses it)


The IT community has enough trouble getting a few ISPs to upgrade their 
DNS software. How are you going to get millions of general users to 
upgrade?


Web stats show that people are still using IE 5...

--
Wojtek :-)


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


Re: Is the behavior expected?

2008-11-26 Thread Peter Otten
Alphones wrote:

 On 11月26日, 下午9时28分, [EMAIL PROTECTED] wrote:
 Alphones:

  it is a little deferent from other script language.

 See also here:http://en.wikipedia.org/wiki/Dynamic_scope#Dynamic_scoping

 Python doesn't have such automatic closures, probably for performance
 reasons and/or maybe to keep its C implementation simpler (maybe other
 people here can give you an explanation of this, I too am curious).

 Bye,
 bearophile
 
 i encountered this problem when i'm writing a program for packaging
 files.
 the program generates tasks according to description file.
 and tasks are deferent from each other, and should be excuted at the
 last of program.
 
 i have experience on Lua and have learned about scheme and haskell, so
 i wrote the wrong code in python.
 
 now my solution is, using class taskCreator to create tasks and put
 them into tasklist.
 class taskCreator:
 def __init__(self, proc, input, output):
 self.proc = proc
 self.input = input
 self.output = output
 def call(self):
 return self.proc.call(self.input, self.output)
 'proc' is generated by procCreators, it's specified.
 
 it looks more complex than lambda one.
 
 is there any other simple way to implement it?

Yes, you can have closures in Python (you already had one, the getFunc()
function in your initial post). 


Random remarks:

You don't need an explicit call() method, you can make instances callable:
 class A:
... def __init__(self, name):
... self.name = name
... def __call__(self):
... print calling, self.name
...
 a = A(foo)
 a()
calling foo

If your object has just this one method you can instead use a closure:

 def make_a(name):
... def call():
... print calling, name
... return call
...
 a = make_a(bar)
 a()
calling bar

This can be simplified further with some help from the library:

 from functools import partial
 def call(name):
... print calling, name
...
 a = partial(call, baz)
 a()
calling baz

Here is a complete example:

import sys
from functools import partial

def lower(input, output):
output.writelines(line.lower() for line  in input)

def prefix(input, output):
for index_line in enumerate(input):
output.write(%d: %s % index_line)

tasks = [partial(lower, open(tmp.py), sys.stdout),
 partial(prefix, open(tmp.py), sys.stdout)]

for t in tasks:
t()

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


Re: Python surpasses Perl in popularity?

2008-11-26 Thread Steve Holden
Xah Lee wrote:
 On Nov 25, 2:47 pm, Jorgen Grahn [EMAIL PROTECTED] wrote:
 On Mon, 24 Nov 2008 20:25:51 -0500, [EMAIL PROTECTED] [EMAIL PROTECTED] 
 wrote:
 QuotingXahLee[EMAIL PROTECTED]:
 herald: Python surpasses Perl in popularity!
 According to
 ?TIOBE Programming Community Index for November 2008? at
 http://www.tiobe.com/content/paperinfo/tpci/index.html
 it seems that Python has surpassed Perl in popularity this month!
 Interesting topic !
 Hard to take a popularity index seriously when Logo is at #19 and
 Bourne shell at #32 ... and then they suggest that their readers can
 use it to make a strategic decision about what programming language
 should be adopted when starting to build a new software system.
 
 your remark is a bit overzealous. After all, we all know that site is
 websearh based. Although it not some kinda scientific report, but it
 does give some good indication of language popularity, however you
 define that.
 
[... rant omitted ...]
I wondered how long you would be able to resist making your vituperative
remarks. Please stop this rubbish.

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

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


Re: what's so difficult about namespace?

2008-11-26 Thread Xah Lee
Xah Lee wrote:
  i cannot fathom what could possibly be difficult of
  introducing or implementing a namespace mechanism into a language. I
  do not understand, why so many languages that lacks so much needed
  namespace for so long? If it is a social problem, i don't imagine they
  would last so long. It must be some technical issue?

On Nov 26, 8:06 am, Wojtek [EMAIL PROTECTED] wrote:
 Simply put:
 - it was not in the original language specification
 - some hundreds of millions of distributed browsers interpret
 Javascript without namespaces
 - to introduce namespaces into the language would require every browser
 to be replaced (at least if the user comes across a site which uses it)

 The IT community has enough trouble getting a few ISPs to upgrade their
 DNS software. How are you going to get millions of general users to
 upgrade?

 Web stats show that people are still using IE 5...

alright, that's speaks for Javascript.

But how's that apply to, say, Scheme lisp, Emacs lisp, PHP?

In the case of Scheme, i can see that the problem of delay in
introducing namespace is due to the nature of community wanting some
consensus on the most elegant approach.

For emacs lisp, is it prolonged lack of namespace due to lack of
developer resource?

in anycase, the reasons above are social ones. Namely, issues like
backward compatibility, agreement on design, lack of developers. I'd
be very interested if any compiler writer can give technical
perspective on whether introducing namespace to a existing lang is a
problem.

  Xah
∑ http://xahlee.org/

☄


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


Re: Is the behavior expected?

2008-11-26 Thread Michele Simionato
On Nov 26, 2:28 pm, [EMAIL PROTECTED] wrote:
 Alphones:

  it is a little deferent from other script language.

 See also here:http://en.wikipedia.org/wiki/Dynamic_scope#Dynamic_scoping

 Python doesn't have such automatic closures, probably for performance
 reasons and/or maybe to keep its C implementation simpler (maybe other
 people here can give you an explanation of this, I too am curious).

Python has closures which are just fine. The issue here is the for
loop.
In Python (as in Common Lisp) the for loop works by *mutating* a
single
loop index. The closures will get the latest value of the loop index.
In Haskell or Scheme the natural way to define a for loop is by
introducing a new index variable at each iteration: there is no
mutation. Each closure get its own index, with the right value.
It is a design choice: Guido and the Common Lisp implementors
are happy with mutating the loop index. I myself prefer the functional
way.

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


Re: what's so difficult about namespace?

2008-11-26 Thread Stefan Behnel
Xah Lee wrote:
 The IT community has enough trouble getting a few ISPs to upgrade their
 DNS software. How are you going to get millions of general users to
 upgrade?
 
 alright, that's speaks for Javascript.
 
 But how's that apply to, say, Scheme lisp, Emacs lisp, PHP?

Think before you write. It's exactly the same thing. How would you get all
Emacs users in the world to upgrade?

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


Re: what's so difficult about namespace?

2008-11-26 Thread George Sakkis
On Nov 26, 11:42 am, Stefan Behnel [EMAIL PROTECTED] wrote:
 Xah Lee wrote:
  The IT community has enough trouble getting a few ISPs to upgrade their
  DNS software. How are you going to get millions of general users to
  upgrade?

  alright, that's speaks for Javascript.

  But how's that apply to, say, Scheme lisp, Emacs lisp, PHP?

 Think before you write. It's exactly the same thing. How would you get all
 Emacs users in the world to upgrade?

The same way you would get all Python users to upgrade to 3.0 ? It's
not like Joe User runs emacs to edit his grocery store list.

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


Re: what's so difficult about namespace?

2008-11-26 Thread Xah Lee

On Nov 26, 8:42 am, Stefan Behnel [EMAIL PROTECTED] wrote:
 XahLeewrote:
  The IT community has enough trouble getting a few ISPs to upgrade their
  DNS software. How are you going to get millions of general users to
  upgrade?

  alright, that's speaks for Javascript.

  But how's that apply to, say, Scheme lisp, Emacs lisp, PHP?

 Think before you write. It's exactly the same thing. How would you get all
 Emacs users in the world to upgrade?

Hi Stefan, try not to be a moron.

In the case of javascript, it involves web servers and clients (web
browsers). In the case of Scheme Lisp or Emacs Lisp, there's no such
server/client issue. There is still the compatibilty issue, but not
the same scenario as javascript. As compatibility issue, that doesn't
just apply to namespaces but to any othe function or change in the
language. And as you know, language changes all the time, in big or
small dosages. Small changes happens almost every release. Major
changes happens every few years (e.g. Java versions thru the year,
Perl4 to perl5, each iteration of Scheme's RnRS) So, in general,
backward compatibility does not fully answer the question of the no
namespace problem. Even if it does, the detail or reason is not given
in the above and is not something obvious at least to me.

  Xah
∑ http://xahlee.org/

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


Re: what's so difficult about namespace?

2008-11-26 Thread Xah Lee
Xah Lee wrote:
 i cannot fathom what could possibly be difficult of
 introducing or implementing a namespace mechanism into a language.

Joshua Cranmer wrote:
 Namespaces go to the very core of a language, name resolution.
 Retroactively adding such a feature is extremely difficult because there
 is a strong chance of accidentally breaking existing code.

Xah Lee wrote:
  could you give some technical detail on this?

  i don't know compiler so am probably being foolish here... but i
  suppose ultimately name resolution and storage at heart is something
  like a hashtable...  namely,

  put ‹identifier 1› table
  put ‹identifier 2› table

  and lookup is just

  retrieve ‹identifier› table

  and now suppose we introduced namespace, so i imagine the compiler
  simply just concat namespace component befor put, and split before
  retrieve?

Steve Holden wrote:
 And therein lies the danger of imagination.

 Typically the namespace components are looked up one by one, so for

this.that.theother

 first this will be looked up and (hopefully) yield an object with a
 namespace, which will then be searched for that, yielding another
 object with a namespace in which theother can be looked up. That's
 certainly how it works in Python:

yes, but Steve, what is your point?

The question is, what is the technical difficulty, if any, of
introducing namespace into a existing language.

You pointed out that identifier lookup at least from the perspective
of language user is somewhat like a tree walking processing. However,
that does not answer the main question.

  Xah
∑ http://xahlee.org/

☄

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


Re: what's so difficult about namespace?

2008-11-26 Thread Hendrik van Rooyen
 Steve Holden [EMAIL PROTECTED] wrote:

 And before anyone bothers to point it out, yes, I know PHO now (finally)
 has namespaces.

I cannot resist oulling the oiss... Its not the first time...

:-)

- Hendrik

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


Re: Getting in to metaprogramming

2008-11-26 Thread Hendrik van Rooyen

 Steven D'Aprano steau wrote:

 
 Well, I don't know about any problem. And it's not so much about 
 whether metaprograms can solve problems that can't be solved by anything 
 else, as whether metaprograms can solve problems more effectively than 
 other techniques.
 
 If you include factory functions, class factories, the builder design 
 pattern, metaclasses, etc. as metaprogramming, then I use it all the 
 time, and find it an excellent technique to use.
 
 But if you mean using a Python program to generate Python source code, 
 then I can't think of any time I used it. Which doesn't mean that others 
 don't find it helpful, only that I haven't yet.

I am using the term in the restricted sense of Python writing Python source.

Given that, can anybody think of an example that you could not do with 
a class?  (excepting the stored procedure aspect)

Or can I claim a new a new meta - rule - I would call it van Rooyen's folly...

 
 Thinking further back, when I was young and programming in Apple's 
 Hypercard 4GL, I used to frequently use Hypercard scripts to generate new 
 Hypercard scripts. That was to work around the limitations of the 
 scripting language.

What sort of stuff did you do, and would having had simple OO available
have rendered it unnecessary?

 
 I don't think metaprogramming in the limited sense (programs to output 
 source code) is a bad idea, but I do think that there are probably better 
 alternatives in a language like Python.
 
 
True. No argument here - I was just wondering if the relationship holds.

- Hendrik

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


import in a class

2008-11-26 Thread TP
Hi everybody,

Here is a file test_import_scope.py:
##
class a():
   import re
   def __init__( self ):
  if re.search( to, toto ):
 self.se = ok!
   def print_se( self ):
  print self.se
a().print_se()
##

When python executes this file, we obtain an error:

$ python test_import_scope.py
[...]
NameError: global name 're' is not defined

Why?

When the re module is imported in the __init__ function or out of the class
(at the top of the file), it works obviously perfectly.

Thanks in advance,

Julien

-- 
python -c print ''.join([chr(154 - ord(c)) for c in '*9(9(18%.91+,\'Z
(55l4('])

When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong. (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


Re: import in a class

2008-11-26 Thread Chris Rebert
On Wed, Nov 26, 2008 at 9:30 AM, TP [EMAIL PROTECTED] wrote:
 Hi everybody,

 Here is a file test_import_scope.py:
 ##
 class a():
   import re
   def __init__( self ):
  if re.search( to, toto ):
 self.se = ok!
   def print_se( self ):
  print self.se
 a().print_se()
 ##

 When python executes this file, we obtain an error:

 $ python test_import_scope.py
 [...]
 NameError: global name 're' is not defined

 Why?

Because Python doesn't look in class-scope when doing name resolution.
It checks the local [function] namespace, then any nested [function]
scopes (not applicable in this case), then the module/global
namespace, and finally the builtins namespace. The class' namespace
never comes into the equation.

Consider this simpler example (remember that `import` assigns a module
to its name in the importing scope):
 class Foo(object):
... A=1
... def foo(self): print A
...
 Foo().foo()
Traceback (most recent call last):
  File stdin, line 1, in module
  File stdin, line 3, in foo
NameError: global name 'A' is not defined

So in foo(), `A` can be accessed by Foo.A or self.A, but not just plain `A`.
I agree it's not entirely intuitive, but remember that Python != Java.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


 When the re module is imported in the __init__ function or out of the class
 (at the top of the file), it works obviously perfectly.

 Thanks in advance,

 Julien

 --
 python -c print ''.join([chr(154 - ord(c)) for c in '*9(9(18%.91+,\'Z
 (55l4('])

 When a distinguished but elderly scientist states that something is
 possible, he is almost certainly right. When he states that something is
 impossible, he is very probably wrong. (first law of AC Clarke)
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Is it possible (and wise) to extend the None-type ?

2008-11-26 Thread Stef Mientki

hello,

I've the idea that I always have a lot of useless code in my programs,
like the next example.

 def _On_Menu_File_Open ( self, event = None ):
   if event :
event.Skip ()

instead of

 def _On_Menu_File_Open ( self, event = None ):
  event.Skip ()

So I would like to extend the None-type (if that's possible),
with a dummy Skip() method.

Is it wise to do ?
If not what are the disadvantages ?

thanks,
Stef Mientki



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


best IDE

2008-11-26 Thread asit
Which one is the best IDE for python 
--
http://mail.python.org/mailman/listinfo/python-list


Re: best IDE

2008-11-26 Thread Chris Rebert
On Wed, Nov 26, 2008 at 9:59 AM, asit [EMAIL PROTECTED] wrote:
 Which one is the best IDE for python 

This was recently discussed. To avoid needlessly rehashing said
discussion, see the thread at
http://groups.google.com/group/comp.lang.python/browse_thread/thread/7fd136aef1c63e47/fbaff90068f0fe02

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

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

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


Re: best IDE

2008-11-26 Thread asit
On Nov 26, 11:09 pm, Chris Rebert [EMAIL PROTECTED] wrote:
 On Wed, Nov 26, 2008 at 9:59 AM, asit [EMAIL PROTECTED] wrote:
  Which one is the best IDE for python 

 This was recently discussed. To avoid needlessly rehashing said
 discussion, see the thread 
 athttp://groups.google.com/group/comp.lang.python/browse_thread/thread/...

 Cheers,
 Chris
 --
 Follow the path of the Iguana...http://rebertia.com

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

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


Re: Is it possible (and wise) to extend the None-type ?

2008-11-26 Thread Chris Rebert
On Wed, Nov 26, 2008 at 9:55 AM, Stef Mientki [EMAIL PROTECTED] wrote:
 hello,

 I've the idea that I always have a lot of useless code in my programs,
 like the next example.

  def _On_Menu_File_Open ( self, event = None ):
   if event :
event.Skip ()

 instead of

  def _On_Menu_File_Open ( self, event = None ):
  event.Skip ()

 So I would like to extend the None-type (if that's possible),

It's not. You can't graft new methods onto NoneType (a.k.a.
type(None)), and you can't subclass NoneType either.
You might be interested in the recipe for a Null type:
http://code.activestate.com/recipes/68205/

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

 with a dummy Skip() method.

 Is it wise to do ?
 If not what are the disadvantages ?

 thanks,
 Stef Mientki



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

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


Re: Getting in to metaprogramming

2008-11-26 Thread Kay Schluehr
On 27 Nov., 05:41, Hendrik van Rooyen [EMAIL PROTECTED] wrote:

 Given that, can anybody think of an example that you could not do with
 a class?  (excepting the stored procedure aspect)

I just noticed that corepy 1.0 [1] has been released. Corepy is an
embedded DSL for synthesizing machine code from chaining Python
commands. This means it provides objects and exploits control
structures used to create machine code that can finally be executed
interactively.

Let's say you have an ordinary Python function that computes a CRC 32.
Now you could attempt to translate the function into other Python code
that expresses a corepy routine. You could create a decorator that
works as follows

1) reads the source of the decorated function
2) transforms the source into corepy source and compiles it or
3) if 2) fails it just returns the passed code object.

Kay

[1] http://www.corepy.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reg Expression - Get position of

2008-11-26 Thread Jorgen Grahn
On Wed, 26 Nov 2008 01:48:59 -0800 (PST), M_H [EMAIL PROTECTED] wrote:
 On Nov 25, 11:06 pm, r [EMAIL PROTECTED] wrote:
 On Nov 25, 4:33 pm, Jorgen Grahn [EMAIL PROTECTED] wrote:

...

  Depends on if you have an irrational fear of REs or not ... I agree
  that REs are overused for things which are better done with split, but
  in this case I think an RE would be clearer.

   re.sub('.*', '', 'dkjkdjdd')

...

 I want to have the end-position of the mimetype tag (position as
 mystr.find('') returns, so I can use the number for a loop)
 However, I can't use just the '' because the character  could also
 be in the string of mimetype (I know, actually not in mimetype, but
 let's assume it).
 So that is why the filter shall be bulletproof and check for '' -
 with possible spaces between both characters.

OK. I am too tired to think it through, but if you need to handle
nesting brackets or escaped brackets (e.g. ignore brackets inside
double-quoted strings) then an RE is not the best solution.

/Jorgen

-- 
  // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.se  R'lyeh wgah'nagl fhtagn!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible (and wise) to extend the None-type ?

2008-11-26 Thread John Machin
On Nov 27, 4:55 am, Stef Mientki [EMAIL PROTECTED] wrote:
 hello,

 I've the idea that I always have a lot of useless code in my programs,
 like the next example.

   def _On_Menu_File_Open ( self, event = None ):
     if event :
      event.Skip ()

 instead of

   def _On_Menu_File_Open ( self, event = None ):
    event.Skip ()

 So I would like to extend the None-type (if that's possible),
 with a dummy Skip() method.

 Is it wise to do ?

No.

 If not what are the disadvantages ?

Assume that as well as your Event class, you also have a Foo class
with a dothis method and a Bar class with a dothat1 and a dothat2
method: you would need to extend the None-type (if that's possible) to
have dummy skip, dothis, dothat1 and dothat2 methods. Each time you
invent a new class, you need to consider adding one or more new dummy
methods to your extended None-type.

Alternative (if you *really* want to save the explicit test) is to
attach the behaviour modification to the *relevant* class:

class NonEvent(Event):
   def do_nothing(self):
  pass
   skip = jump = hop = waltz = saunter = do_nothing
   def __len__(self):
  return 0
NON_EVENT = NonEvent()
del NonEvent

# later:

def amethod(self, event=NON_EVENT):
   if event: # still works thanks to __len__ above
  event.skip()
   # now can avoid test, if desired
   event.skip()

HTH ... BTW, ever heard of PEP 8?

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


Re: best IDE

2008-11-26 Thread Mike Driscoll
On Nov 26, 11:59 am, asit [EMAIL PROTECTED] wrote:
 Which one is the best IDE for python 

You'll probably also want to take a look at the Python wiki:

http://wiki.python.org/moin/PythonEditors

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


newbie question

2008-11-26 Thread Nan
Hello,
   I just started to use Python. I wrote the following code and
expected 'main' would be called.

def main():
  print hello

main

But I was wrong. I have to use 'main()' to invoke main. The python
interpreter does not give any warnings for the above code. Is there
any way/tool to easily detect this kind of errors ?

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


Python equivalent of Common Lisp Macros?

2008-11-26 Thread dpapathanasiou
I'm using the feedparser library to extract data from rss feed items.

After I wrote this function, which returns a list of item titles, I
noticed that most item attributes would be retrieved the same way,
i.e., the function would look exactly the same, except for the single
data.append line inside the for loop.

In CL, I could simply write a macro, then replace the data.append line
depending on which attribute I wanted.

Is there anything similar in Python?

Here's the function:

def item_titles (feed_url):
Return a list of the item titles found in this feed url
data = []
feed = feedparser.parse(feed_url)
if feed:
if len(feed.version)  0:
for e in feed.entries:
data.append(e.title.encode('utf-8'))
return data
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie question

2008-11-26 Thread Albert Hopkins
On Wed, 2008-11-26 at 11:11 -0800, Nan wrote:
 Hello,
I just started to use Python. I wrote the following code and
 expected 'main' would be called.
 
 def main():
   print hello
 
 main
 
 But I was wrong. I have to use 'main()' to invoke main. The python
 interpreter does not give any warnings for the above code. Is there
 any way/tool to easily detect this kind of errors ?
 

Syntactically your code is correct, so the interpreter just goes about
its business.  You can usually use tools such as pylint or pychecker to
find find such issues. For example, pylint reports (among other things):

W:  4: Statement seems to have no effect


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


Re: newbie question

2008-11-26 Thread Chris Rebert
On Wed, Nov 26, 2008 at 11:11 AM, Nan [EMAIL PROTECTED] wrote:
 Hello,
   I just started to use Python. I wrote the following code and
 expected 'main' would be called.

 def main():
  print hello

 main

 But I was wrong. I have to use 'main()' to invoke main. The python
 interpreter does not give any warnings for the above code. Is there
 any way/tool to easily detect this kind of errors ?

Python has first-class functions, so you can pass a function to
another function (so the line `main` has a meaning, just not a useful
one). Also, Python doesn't do compile-time typechecking, so it has no
way of knowing that `main` is a function and not a plain variable
until runtime. Thus, the parentheses are required for a function call
even when there are no arguments.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com


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

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


Re: Instance attributes vs method arguments

2008-11-26 Thread Aahz
In article [EMAIL PROTECTED],
M.-A. Lemburg [EMAIL PROTECTED] wrote:

It is always good practice to provide default values for instance
variables in the class definition, both to enhance readability and to
allow adding documentation regarding the variables, e.g.

Actually, my company uses an occasional pattern of detecting whether an
attribute has ever been set with hasattr().  I am not particularly fond
of that mechanism because it has been the occasional source of subtle
bugs, but I also see the utility.
-- 
Aahz ([EMAIL PROTECTED])   * http://www.pythoncraft.com/

It is easier to optimize correct code than to correct optimized code.
--Bill Harlan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python equivalent of Common Lisp Macros?

2008-11-26 Thread Chris Rebert
On Wed, Nov 26, 2008 at 11:13 AM, dpapathanasiou
[EMAIL PROTECTED] wrote:
 I'm using the feedparser library to extract data from rss feed items.

 After I wrote this function, which returns a list of item titles, I
 noticed that most item attributes would be retrieved the same way,
 i.e., the function would look exactly the same, except for the single
 data.append line inside the for loop.

 In CL, I could simply write a macro, then replace the data.append line
 depending on which attribute I wanted.

 Is there anything similar in Python?

Yes, use higher-order functions. See below.


 Here's the function:

 def item_titles (feed_url):
Replace previous line with:
def item_titles(feed_url, attr_getter):
Return a list of the item titles found in this feed url
data = []
feed = feedparser.parse(feed_url)
if feed:
if len(feed.version)  0:
for e in feed.entries:
data.append(e.title.encode('utf-8'))
Replace previous line with:
data.append(attr_getter(e))
return data

Example usage:

def title_getter(entry):
return entry.title.encode('utf-8')

titles = item_titles(some feed url here, title_getter)

As I'm not familiar with feedparser, you might want to move where the
.encode() takes place, but you get the idea.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

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

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


Re: Python equivalent of Common Lisp Macros?

2008-11-26 Thread Diez B. Roggisch

dpapathanasiou schrieb:

I'm using the feedparser library to extract data from rss feed items.

After I wrote this function, which returns a list of item titles, I
noticed that most item attributes would be retrieved the same way,
i.e., the function would look exactly the same, except for the single
data.append line inside the for loop.

In CL, I could simply write a macro, then replace the data.append line
depending on which attribute I wanted.

Is there anything similar in Python?

Here's the function:

def item_titles (feed_url):
Return a list of the item titles found in this feed url
data = []
feed = feedparser.parse(feed_url)
if feed:
if len(feed.version)  0:
for e in feed.entries:
data.append(e.title.encode('utf-8'))
return data


No, there are no macros. Yet it has - amongst other options, such as 
callbacks - decorators, that would allow you to write your code like this:


def items (feed_url):
feed = feedparser.parse(feed_url)
if feed:
if len(feed.version)  0:
for e in feed.entries:
yield e


titles = []
other_things = []
for item in items(url):
titles.append(item.title.encode('utf-8'))
other_things.append(item.other_thing)

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


Re: Getting in to metaprogramming

2008-11-26 Thread Terry Reedy

Hendrik van Rooyen wrote:


I am using the term in the restricted sense of Python writing Python source.

Given that, can anybody think of an example that you could not do with 
a class?  (excepting the stored procedure aspect)


I am not sure I understand your question.

def iterize(recursive_function_text):
code to parse input and fill a template
return equivalent_iterative_function_text

where input and output are both Python code.  If one were to implement 
this by compiling the input to AST form and then walking the tree, the 
AST node classes would be involved, but I would scarely say the 
translation was done by the classes, as opposed to functions which might 
or might not be attacked to a class as methods.


tjr

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


Re: Python equivalent of Common Lisp Macros?

2008-11-26 Thread Arnaud Delobelle
dpapathanasiou [EMAIL PROTECTED] writes:

 I'm using the feedparser library to extract data from rss feed items.

 After I wrote this function, which returns a list of item titles, I
 noticed that most item attributes would be retrieved the same way,
 i.e., the function would look exactly the same, except for the single
 data.append line inside the for loop.

 In CL, I could simply write a macro, then replace the data.append line
 depending on which attribute I wanted.

 Is there anything similar in Python?

 Here's the function:

 def item_titles (feed_url):
 Return a list of the item titles found in this feed url
 data = []
 feed = feedparser.parse(feed_url)
 if feed:
 if len(feed.version)  0:
 for e in feed.entries:
 data.append(e.title.encode('utf-8'))
 return data

Something like this?

def item_attrs (feed_url, attr):
Return a list of the item titles found in this feed url
data = []
feed = feedparser.parse(feed_url)
if feed:
if len(feed.version)  0:
for e in feed.entries:
data.append(getattr(e, attr).encode('utf-8'))
return data

You're not making it clear how the data.append... line changes so it's
hard to know exactly.

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


Re: Is it possible (and wise) to extend the None-type ?

2008-11-26 Thread Terry Reedy

Stef Mientki wrote:

hello,

I've the idea that I always have a lot of useless code in my programs,
like the next example.

 def _On_Menu_File_Open ( self, event = None ):
   if event :
event.Skip ()

instead of

 def _O

So I would like to extend the None-type (if that's possible),
with a dummy Skip() method.


def Skipper(object):
def Skip(): pass
skipper = Skipper()

def _On_Menu_File_Open ( self, event = skipper ):
   event.Skip ()

etc.

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


Re: Python equivalent of Common Lisp Macros?

2008-11-26 Thread J Kenneth King
dpapathanasiou [EMAIL PROTECTED] writes:

 I'm using the feedparser library to extract data from rss feed items.

 After I wrote this function, which returns a list of item titles, I
 noticed that most item attributes would be retrieved the same way,
 i.e., the function would look exactly the same, except for the single
 data.append line inside the for loop.

 In CL, I could simply write a macro, then replace the data.append line
 depending on which attribute I wanted.

 Is there anything similar in Python?

 Here's the function:

 def item_titles (feed_url):
 Return a list of the item titles found in this feed url
 data = []
 feed = feedparser.parse(feed_url)
 if feed:
 if len(feed.version)  0:
 for e in feed.entries:
 data.append(e.title.encode('utf-8'))
 return data

No macros -- need the whole code as data paradigm which doesn't exist
in python.

The pythonic way to create the sort of abstraction you're looking for
would be to use the *attr functions and either a map of attribute
identities or inspect the attributes from the objects.

Some UNTESTED code...

def extract_entry(e, attrs=['title', 'datetime', 'article']):
out = []
for attr in attrs:
assert hasattr(e, attr)
out.append(getattr(e, attr))
return out

Using the inspect module would give an even more generic function, but
with more complex code of course.

Then your code would look more like:

def items(feed_url):
feed = feedparser.feed(feed_url)
if feed and len(feed)  0:
return [extract_entry(entry) for entry in feed.entries]

Of course, I'm making liberal assumptions about what you're looking for
in your ouput here... but it's just an example, not a full
solution. YMMV. Hope it helps. :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: what's so difficult about namespace?

2008-11-26 Thread Gene
On Nov 26, 9:15 am, Xah Lee [EMAIL PROTECTED] wrote:
 On Nov 26, 5:45 am, Joshua Cranmer [EMAIL PROTECTED] wrote:

   i cannot fathom what could possibly be difficult of
   introducing or implementing a namespace mechanism into a language.

  Namespaces go to the very core of a language, name resolution.
  Retroactively adding such a feature is extremely difficult because there
  is a strong chance of accidentally breaking existing code.

 could you give some technical detail on this?

 i don't know compiler so am probably being foolish here... but i
 suppose ultimately name resolution and storage at heart is something
 like a hashtable...  namely,

 put ‹identifier 1› table
 put ‹identifier 2› table

 and lookup is just

 retrieve ‹identifier› table

 and now suppose we introduced namespace, so i imagine the compiler
 simply just concat namespace component befor put, and split before
 retrieve?

   Xah
 ∑http://xahlee.org/

 ☄

I'm sorry for the earlier post.  I read your question too quickly.

I've implemented a few research compilers; none in production.  You're
totally right in the case where the language has general nested
lexical scoping.  Namespaces just add an outermost scope.  If you've
done a good engineering job, the compiler change is trivial. In fact I
added namespaces like this to an assembler that had lexical scoping.
It took about an hour including writing a test suite.

If you already have a bunch of compilers for a language like pre-
namespace C or Javascript or Basic that doesn't allow for lexical
scoping, then the addition is likely to be non-trivial because the
implementation compiler language is often C and C programmers will
tend to declare a single, global symbol table.  So adding a separate
outer scope involves hunting down all the global references and
replacing them with references to the current namespace table.  We can
tut tut about this being bad design, but there you have it...

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


Python+Pyjamas+V8=ftw

2008-11-26 Thread inhahe
I don't know how much the community knows about this - i haven't been 
participating much of late - but here's something amazing.

Apparently javascript is just as dynamic as python, because someone made a 
python-to-javascript converter in just 1200 line (pyjamas).  Meanwhile 
google's new javascript engine (v8) blew all the others out the water, 
raising the bar - and now safari and firefox already have already risen to 
that bar with their own jit js engines.

The exciting thing is that python code converted to javascript runs on v8 10 
times faster (http://www.advogato.org/article/985.html).

Thus google's strategy in making the JIT compiler represents what Python 
could (and should) be.  Python should either adapt v8, Tamarin 
(http://en.wikipedia.org/wiki/Tamarin_(JavaScript_engine), or similar to 
make its own JIT, or take their basic principles 
(http://www.youtube.com/watch?v=lZnaaUoHPhs) and recreate them for its own 
JIT from scratch.

Until then, we can always install v8/tamarin/tracemonkey/squirrelfish and 
easily make a front-end that automatically uses pyjamas to convert python 
script to JS and runs it.  Perhaps pyjamas needs some improvement to fully 
implement Python - the homepage isn't very clear on how exactly the JS 
implementation mirrors the Python implementation.  Also I suppose it doesn't 
support Python 3.0 and would have to be changed to support that.


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


Re: Python equivalent of Common Lisp Macros?

2008-11-26 Thread dpapathanasiou
On Nov 26, 2:30 pm, Chris Rebert [EMAIL PROTECTED] wrote:
 On Wed, Nov 26, 2008 at 11:13 AM, dpapathanasiou

 [EMAIL PROTECTED] wrote:
  I'm using the feedparser library to extract data from rss feed items.

  After I wrote this function, which returns a list of item titles, I
  noticed that most item attributes would be retrieved the same way,
  i.e., the function would look exactly the same, except for the single
  data.append line inside the for loop.

  In CL, I could simply write a macro, then replace the data.append line
  depending on which attribute I wanted.

  Is there anything similar in Python?

 Yes, use higher-order functions. See below.



  Here's the function:

  def item_titles (feed_url):

 Replace previous line with:
 def item_titles(feed_url, attr_getter):Return a list of the item 
 titles found in this feed url
 data = []
 feed = feedparser.parse(feed_url)
 if feed:
 if len(feed.version)  0:
 for e in feed.entries:
 data.append(e.title.encode('utf-8'))

 Replace previous line with:
 data.append(attr_getter(e))

 return data

 Example usage:

 def title_getter(entry):
 return entry.title.encode('utf-8')

 titles = item_titles(some feed url here, title_getter)

Thanks; this is exactly what I was looking for.


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


asp versus cgi

2008-11-26 Thread davidj411
when i use cgi, i never get a 500 error but i can see how it might
take on overhead if many users are hitting the site at once. so to
avoid this, i looked into registering the python engine for ASP
requests.

when i use asp (C:\WINDOWS\system32\inetsrv\asp.dll fileversion
info:--a-- W32i   DLL ENU   5.1.2600.5512 shp369,664 04-14-2008
asp.dll) , i get intermittent results. it either works or generates a
500 error. the error pattern is 200, 500, 200, 500, 200, 500 and so
on.


this is the ASP code when using GET method:

%@ LANGUAGE = Python%

%
import sys
sys.stdout=sys.stdin
usr = Request.QueryString(usr)

Response.Write (usr)
%
**
this is the ASP code when using the POST method
%@ LANGUAGE = Python%

%
import sys
sys.stdout=sys.stdin
usr = Request.Form (usr)
Response.Write (str(usr))
%
**

POST by the way seems to have a 100 kb limit so why ever use it unless
you need to keep the data out of the URL?)
--
http://mail.python.org/mailman/listinfo/python-list


hello from colombia

2008-11-26 Thread fel
I work in a small software company using php all day, I wish the usage
of Python was more common within my company
they are starting a new project (insurance stuff) using Java, and I
just hate that eventually I'l be debugging someone-else's java code
how can I convince them that Python is better, and get them to re-
think their strategy?

also, kuddos on the language, you serve mankind as few do.



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


asp oddness , why specify ASP twice

2008-11-26 Thread davidj411
for some reason this code works:
*
%@ LANGUAGE = Python%
%
Response.Write (test)
%
*


but this code does NOT:
*
%@ LANGUAGE = Python
Response.Write (test)
%
*

the difference between the two is that i remove % from the first
line and removed % from the next line.
it would seem that this should put all the code into one ASP block
but for some reason it does not run.

any ideas? thanks
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible (and wise) to extend the None-type ?

2008-11-26 Thread Jason Scheirer
On Nov 26, 11:40 am, Terry Reedy [EMAIL PROTECTED] wrote:
 Stef Mientki wrote:
  hello,

  I've the idea that I always have a lot of useless code in my programs,
  like the next example.

   def _On_Menu_File_Open ( self, event = None ):
     if event :
      event.Skip ()

  instead of

   def _O

  So I would like to extend the None-type (if that's possible),
  with a dummy Skip() method.

 def Skipper(object):
      def Skip(): pass
 skipper = Skipper()

 def _On_Menu_File_Open ( self, event = skipper ):
     event.Skip ()

 etc.

I think this methods works best, but quite frankly, if a method is
only two lines long, then you've likely got a code smell and no amount
of over-design is going to cover for it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible (and wise) to extend the None-type ?

2008-11-26 Thread Stef Mientki

snip

Alternative (if you *really* want to save the explicit test) is to
attach the behaviour modification to the *relevant* class:

class NonEvent(Event):
   def do_nothing(self):
  pass
   skip = jump = hop = waltz = saunter = do_nothing
   def __len__(self):
  return 0
NON_EVENT = NonEvent()
del NonEvent

# later:

def amethod(self, event=NON_EVENT):
   if event: # still works thanks to __len__ above
  event.skip()
   # now can avoid test, if desired
   event.skip()

  

thanks guys, the Null, Dummy, Skipper, Nonevent class works great

HTH ... BTW, ever heard of PEP 8?
  

I guess Python is missing some kind of CSS ;-)

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


Re: what's so difficult about namespace?

2008-11-26 Thread Kaz Kylheku
On 2008-11-26, Xah Lee [EMAIL PROTECTED] wrote:
 comp.lang.lisp,comp.lang.functional,comp.lang.perl.misc,comp.lang.python,comp.lang.java.programmer

 2008-11-25

 Recently, Steve Yegge implemented Javascript in Emacs lisp, and
 compared the 2 languages.

 http://steve-yegge.blogspot.com/
 http://code.google.com/p/ejacs/

 One of his point is about emacs lisp's lack of namespace.

 Btw, there's a question i have about namespace that always puzzled me.

 In many languages, they don't have namespace and is often a well known
 sour point for the lang. For example, Scheme has this problem up till
 R6RS last year.

Scheme hasn't officially supported breaking a program into multiple files until
R6RS. If the language is defined in terms of one translation unit, it doesn't
make sense to have a namespace feature.

 PHP didn't have namespace for the past decade till
 about this year. Javascript, which i only have working expertise,
 didn't have namespace as he mentioned in his blog.

Javascript programs are scanned at the character level by the browser as part
of loading a page.  So there are severe practical limitations on how large
Javascript programs can be.

Namespaces are useful only in very large programs.

 Elisp doesn't have
 name space and it is a well known major issue.

C doesn't have namespaces, and yet you have projects like the Linux kernel
which get by without this.

Given that the Linux kernel can do without namespaces, it's easy to see how
Javascript and Elisp can survive without it.

 Of languages that do have namespace that i have at least working
 expertise: Mathematica, Perl, Python, Java. Knowing these langs
 sufficiently well, i do not see anything special about namespace. The
 _essence_ of namespace is that a char is choosen as a separator, and
 the compiler just use this char to split/connect identifiers.

The essence of a true namespace or package system or whatever is that you can
establish situations in which you use the unqualified names.

You can emulate namespaces by adding prefixes to identifiers, which is
how people get by in C.

In C, you can even get the functionality of short names using the preprocessor.

I have done this before (but only once). In a widely-used public header file, I
prefixed all of the names of struct members (because struct members are not
immune to clashes: they clash with preprocessor symbols!)

  struct foo {
int foo_category;
time_t foo_timestamp;
/* ... */
  }

Inside the implementation module, I made macros for myself:

  #define category foo_category
  #define timestamp foo_timestamp

In this way, I didn't have to edit any of the code in order to move the struct
members into the namespace. Expressions like ``pf-category'' continued to work
as before.

 Although i have close to zero knowledge about compiler or parser, but
 from a math point of view and my own 18 years of programing
 experience, i cannot fathom what could possibly be difficult of
 introducing or implementing a namespace mechanism into a language.

The same things that make it difficult to add anything to a language, namely
the stupid way in which languages are designed to get in the way of extension.

What would it take to add namespaces to C, for instance?

If you have any proposal for a new C feature, the ISO C people encourage you to
develop a proof-of-concept, which means: hack it into an existing
implementation to demonstrate that it's feasible.

If you need new syntax, hacking it into an implementation means hacking it into
the parser. Everyone who wants to experiment with your feature needs to get
your compiler patches (for GCC for instance) and rebuild the compiler.

The process is painful enough that it's only worth doing if it solves something
that is perceived as being a critical issue.

 do not understand, why so many languages that lacks so much needed
 namespace for so long? If it is a social problem, i don't imagine they
 would last so long. It must be some technical issue?

I recently read about a very useful theory which explains why technologies
succeed or fail. 

See: 
http://arcfn.com/2008/07/why-your-favorite-programming-language-is-unpopular.html

The perceived crisis which namespaces solve is not sigificant enough relative
to the pain of adoption.  No, wrong, let's restate that. Programmers do use
namespaces even when there is no language feature. It's not about adoption of
namespaces, but adoption of proper support for namespaces.  Not using
namespaces is a crisis in a software project, but (at least in the perception
held by many programmers) that crisis is adequately mitigated by using a naming
convention.  Proper namespaces only address the small remaining vestiges
of the original crisis.

Thus: the perceived crisis which is solved by properly incorporating namespaces
into a programming language (rather than living with a prefix-based emulation)
is not significant enough relative to the perceived pain of adopting proper
namespaces into the programming 

Re: Is it possible (and wise) to extend the None-type ?

2008-11-26 Thread Stef Mientki

Jason Scheirer wrote:

On Nov 26, 11:40 am, Terry Reedy [EMAIL PROTECTED] wrote:
  

Stef Mientki wrote:


hello,
  
I've the idea that I always have a lot of useless code in my programs,

like the next example.
  
 def _On_Menu_File_Open ( self, event = None ):

   if event :
event.Skip ()
  
instead of
  
 def _O
  
So I would like to extend the None-type (if that's possible),

with a dummy Skip() method.
  

def Skipper(object):
 def Skip(): pass
skipper = Skipper()

def _On_Menu_File_Open ( self, event = skipper ):
event.Skip ()

etc.



I think this methods works best, but quite frankly, if a method is
only two lines long, then you've likely got a code smell and no amount
of over-design is going to cover for it.
  
Sorry I should have said that I only showed the relevant (to this issue) 
part,

and this kind of if statements occurs quit a lot.

Probably I should not say this here on this list,
but to give you the whole truth,
I often forget the if-statement ( because it has really nothing to do 
with the functionality I intend to write),

and then my program crashes (unexpected) :-(

cheers,
Stef

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


Re: what's so difficult about namespace?

2008-11-26 Thread MRAB

Kaz Kylheku wrote:

On 2008-11-26, Xah Lee [EMAIL PROTECTED] wrote:

comp.lang.lisp,comp.lang.functional,comp.lang.perl.misc,comp.lang.python,comp.lang.java.programmer

2008-11-25

Recently, Steve Yegge implemented Javascript in Emacs lisp, and
compared the 2 languages.

http://steve-yegge.blogspot.com/
http://code.google.com/p/ejacs/

One of his point is about emacs lisp's lack of namespace.

Btw, there's a question i have about namespace that always puzzled me.

In many languages, they don't have namespace and is often a well known
sour point for the lang. For example, Scheme has this problem up till
R6RS last year.


Scheme hasn't officially supported breaking a program into multiple files until
R6RS. If the language is defined in terms of one translation unit, it doesn't
make sense to have a namespace feature.


PHP didn't have namespace for the past decade till
about this year. Javascript, which i only have working expertise,
didn't have namespace as he mentioned in his blog.


Javascript programs are scanned at the character level by the browser as part
of loading a page.  So there are severe practical limitations on how large
Javascript programs can be.

Namespaces are useful only in very large programs.


Elisp doesn't have
name space and it is a well known major issue.


C doesn't have namespaces, and yet you have projects like the Linux kernel
which get by without this.

Given that the Linux kernel can do without namespaces, it's easy to see how
Javascript and Elisp can survive without it.


Of languages that do have namespace that i have at least working
expertise: Mathematica, Perl, Python, Java. Knowing these langs
sufficiently well, i do not see anything special about namespace. The
_essence_ of namespace is that a char is choosen as a separator, and
the compiler just use this char to split/connect identifiers.


The essence of a true namespace or package system or whatever is that you can
establish situations in which you use the unqualified names.

You can emulate namespaces by adding prefixes to identifiers, which is
how people get by in C.

In C, you can even get the functionality of short names using the preprocessor.

I have done this before (but only once). In a widely-used public header file, I
prefixed all of the names of struct members (because struct members are not
immune to clashes: they clash with preprocessor symbols!)

  struct foo {
int foo_category;
time_t foo_timestamp;
/* ... */
  }

Inside the implementation module, I made macros for myself:

  #define category foo_category
  #define timestamp foo_timestamp

In this way, I didn't have to edit any of the code in order to move the struct
members into the namespace. Expressions like ``pf-category'' continued to work
as before.


Although i have close to zero knowledge about compiler or parser, but
from a math point of view and my own 18 years of programing
experience, i cannot fathom what could possibly be difficult of
introducing or implementing a namespace mechanism into a language.


The same things that make it difficult to add anything to a language, namely
the stupid way in which languages are designed to get in the way of extension.

What would it take to add namespaces to C, for instance?

If you have any proposal for a new C feature, the ISO C people encourage you to
develop a proof-of-concept, which means: hack it into an existing
implementation to demonstrate that it's feasible.

If you need new syntax, hacking it into an implementation means hacking it into
the parser. Everyone who wants to experiment with your feature needs to get
your compiler patches (for GCC for instance) and rebuild the compiler.

The process is painful enough that it's only worth doing if it solves something
that is perceived as being a critical issue.


do not understand, why so many languages that lacks so much needed
namespace for so long? If it is a social problem, i don't imagine they
would last so long. It must be some technical issue?


I recently read about a very useful theory which explains why technologies
succeed or fail. 


See: 
http://arcfn.com/2008/07/why-your-favorite-programming-language-is-unpopular.html


[snip]
The correct URL is 
http://arcfn.com/2008/07/why-your-favorite-language-is-unpopular.html

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


help with class

2008-11-26 Thread tekion
Hello,
I am playing with class.  Below is the code snippet:
#!/usr/bin/python
  2
  3 class test_class:
  4#import gzip
  5def __init__(self,file):
  6   self.file = file
  7def open_file(self):
  8   try:
  9  print file: %s % self.file
 10  self.xml_file = gzip.GzipFile(self.file,'r')
 11   except:
 12  print an exception has occured
 13   for line in self.xml_file:
 14  print line: %s % line
 15   self.xml_file.close()
 16
 17
 18 if __name__ == '__main__':
 19import gzip
 20import sys
 21t = test_class( sys.argv[1] )
 22t.open_file()

My question are:
1.  Why do I need to use import gzip on main section to get it the
script to work?  I would assume you need the import of gzip in the
class section.
2.  What is the proper way of using module in a class you are creating?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python surpasses Perl in popularity?

2008-11-26 Thread Hrvoje Niksic
Xah Lee [EMAIL PROTECTED] writes:

 Bourne Shell, is pretty much replaced by Bash since several years ago.
 For example, as far as i know, linuxes today don't have Bourne Shell
 anymore. “sh” is just a alias to bash with some compatibility
 parameter.

That used to be the case, but these days 'sh' is as often an alias to
a lighter shell program, a free reimplementation of sh that includes a
much smaller superset of the original sh functionality than that of
bash.  For example, on default Ubuntu installations, sh is a symlink
to dash, a lightweight POSIX-compliant shell derived from ash.
--
http://mail.python.org/mailman/listinfo/python-list


Re: what's so difficult about namespace?

2008-11-26 Thread Tamas K Papp
On Wed, 26 Nov 2008 21:32:24 +, Kaz Kylheku wrote:

 See:
 http://arcfn.com/2008/07/why-your-favorite-programming-language-is-
unpopular.html

That was 404 for me, but

http://arcfn.com/2008/07/why-your-favorite-language-is-unpopular.html

works.  Interesting, thanks for mentioning it.

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


Re: Is it possible (and wise) to extend the None-type ?

2008-11-26 Thread M.-A. Lemburg
On 2008-11-26 18:55, Stef Mientki wrote:
 hello,
 
 I've the idea that I always have a lot of useless code in my programs,
 like the next example.
 
  def _On_Menu_File_Open ( self, event = None ):
if event :
 event.Skip ()
 
 instead of
 
  def _On_Menu_File_Open ( self, event = None ):
   event.Skip ()
 
 So I would like to extend the None-type (if that's possible),
 with a dummy Skip() method.
 
 Is it wise to do ?
 If not what are the disadvantages ?

This doesn't work. None is a Python singleton that cannot be
subclassed.

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Nov 26 2008)
 Python/Zope Consulting and Support ...http://www.egenix.com/
 mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
 mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/

2008-11-12: Released mxODBC.Connect 0.9.3  http://python.egenix.com/

 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter and asyncronous socket

2008-11-26 Thread maxlosblob
On 26 Nov, 13:42, Steve Holden [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  Hi all, I'm new to python and I've been spending the last week on GUI
  that refresh its content based on data periodically coming from a
  remote socket.
  I succeded in doing it (thanks newsgroups and online manual!) using
  theTkinter.after method to implement a busy wait on the socket (which
  I had previously set to non blocking)
  I should be happy with it, but on windows (application must be multi-
  platform) the busy wait leads to a 100% CPU usage. I'm trying to
  implement it the other way round: a socket process that updates a
  label (or a queue object) in the GUI. I can't figure out how to do
  this. Anyone can post hints? With some details, maybe?

 Processes are probably a bit heavyweight for this purpose: they create
 difficulties in communication (unless you use the new multiprocessing
 library in 2.6).

 One approach would be to run the socket code in blocking mode in a
 separate thread started by the (main program) GUI thread at program
 startup, and communicating results back via a Queue.Queue or similar to
 the GUI thread. That thread wakes itself up once every (say) 500 mS to
 check for updates from the socket side.

 You should see your CPU utilization go down then. The threading.thread
 library is actually much easier to use than you would think, though it's
 possible to get things wrong by assuming data sharing will work in ways
 it actually doesn't. But if you have the main thread pass a Queue to the
 networking thread, that should be a reliable means of communication.

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

Thankk you Steve, I have now a GUI and a threaded socket client
receiving data on its socket. I pass to it a queue object from the
GUI, but when it tries to push a value on the queue, the GUI does not
see any value. My last work with OOP is as far in time as the
beginning of Java, I'm surely missing something simple but very
important.
Anyway, the goal to have a responsive GUI and a functional socket has
been achieved, thanks again. If you have hints on the queue problem,
your help is welcome.

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


  1   2   >