Re: how to call a function for evry 10 secs

2011-07-02 Thread anand jeyahar
 >
>  > Hi All,
> > I need to call a function for evry 10 secs
> > how can i achieve this in python
>
>
> import time
> while True:
>time.sleep(10)
>function()
>


Please don't reinvent the wheel...
Use the python apscheduler module.
http://packages.python.org/APScheduler/#installing-apscheduler


Thanks and Regards,
==
Anand Jeyahar
https://sites.google.com/site/<
https://sites.google.com/site/aangjie/home/quotes>
anandjeyahar
==
The man who is really serious,
with the urge to find out what truth is,
has no style at all. He lives only in what is.
 ~Bruce Lee

Love is a trade with lousy accounting policies.
~Aang Jie
-- 
http://mail.python.org/mailman/listinfo/python-list


poll of filesystem

2011-07-02 Thread Belisko Marek
Hi,

just want to use poll method to get data from /proc file system. Use
simple code for it. Problem is it seems poll return POLLIN flag but
when I try to read data it's always empty. Could be a problem changes
are so fast that print can't print it?

Code:

#!/usr/bin/python

import select
from select import POLLIN, POLLERR

p = select.poll()

fd = open("/proc/loadavg", "r")

p.register(fd.fileno(), POLLIN)

while True:
events = p.poll(1000)
if (events == -1):
print "timeout"
fd0, event = events[0]
if (event == POLLIN):
print fd.read()

Thanks,

marek
-- 
as simple and primitive as possible
-
Marek Belisko - OPEN-NANDRA
Freelance Developer

Ruska Nova Ves 219 | Presov, 08005 Slovak Republic
Tel: +421 915 052 184
skype: marekwhite
icq: 290551086
web: http://open-nandra.com
-- 
http://mail.python.org/mailman/listinfo/python-list


How to save a email message?

2011-07-02 Thread TheSaint
Hello,
I'm trying to gather some mail and save it. I don't get why it isn't saved 
as expected.

==

>>> import poplib, socket, sys
>>> from configparser import Error as ProtocolError
>>> args= sys.argv[1:] # this is fake but is here as example

>>> def Pop3_access(*args):
>>>'''Accessing a pop server, doing a function and return a result'''

>>>func= args[0]; args= args[1:]
>>>try:
>>>   pop= poplib.POP3(srv_info[0])
>>>   pop.user(srv_info[1])
>>>   pop.pass_(srv_info[2])
>>>except (poplib.error_proto):
>>>   raise ProtocolError
>>>except (socket.timeout,socket.gaierror):
>>>   try: pop.quit()
>>>   except NameError: pass # it wasn't started
>>>   return
>>>result= func(pop, args)
>>>pop.quit()
>>>return result

>>> def func(pop, N):
...return pop.retr(N)
...
>>> msg= Pop3_access(func, 4)
>>> from io import BytesIO as B
>>> fp= B()
>>> for l in msg[1]:
...fp.write(l)
...fp.write('\n'.encode())
...
34
1
50
1
63
1
65
1
36
1
52
1
41
1
114
1
45
1
38
1
74
1
56
1
37
1
34
1
28
1
23
1
33
1
56
1
57
1
17
1
44
1
31
1
54
1
30
1
30
1
0
1
31
1
0
1
39
1
0
1
12
1
32
1
49
1
0
1
6
1
64
1
68
1
0
1
>>> from mailbox import mbox as Mbx
>>> mbx= Mbx('/tmp/mb', True)
>>> mbx.add(fp)
0
>>> mbx.get_message(0)

>>> print(mbx.get_message(0))


>>>
===

The result is an empty message, but the fp.getvalue() shows file-like 
stream.
Am I missing some point?

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does anyone know of a python tapi module

2011-07-02 Thread Werner Thie

On 7/1/11 11:15 AM, Alister Ware wrote:

The subject probably say is all but to elaborate.

I am looking for a way to communicate with a tapi driver for a PBX so I
can experiment with creating some CTI (Computer Telephony Integration)
software.


I used TAPI since its inception for quite a few projects, but am not 
aware of anything pythonic. Attempting to cough up an interface layer I 
would resort to using Chris Sells tfx wrapper fro TAPI, which helps a 
lot keeping things in check and becoming overly complex.


HTH, Werner

http://books.google.com/books?id=3M_mIvtdGqUC&pg=PA82&lpg=PA82&dq=chris+sell+tfx&source=bl&ots=5UhAxbFTym&sig=7hRn0oUbyZsm_yyDvASKD-AT1jo&hl=en&ei=w2UOTsPlBJOisAP57JyrDg&sa=X&oi=book_result&ct=result&resnum=1&ved=0CBkQ6AEwAA
--
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to chain processes together on a pipeline

2011-07-02 Thread Andrew Berg
This code is working:
> try:
> ffmpeg_proc = subprocess.Popen(queue[position].ffmpeg_cmd,
> stdout=subprocess.PIPE, stderr=open(os.devnull, 'w'))
> except WindowsError as exc:
> log_windows_error(exc, queue[position].ffmpeg_cmd, 'critical')
> break
> if queue[position].vol != 1:
> try:
> sox_proc = subprocess.Popen(queue[position].sox_cmd,
> stdin=ffmpeg_proc.stdout, stdout=subprocess.PIPE,
> stderr=open(os.devnull, 'w'))
> wav_pipe = sox_proc.stdout
> except WindowsError as exc:
> log_windows_error(exc, queue[position].sox_cmd, 'critical')
> break
> finally:
> ffmpeg_proc.stdout.close()
> else:
> wav_pipe = ffmpeg_proc.stdout
> try:
> nero_aac_proc = subprocess.Popen(queue[position].nero_aac_cmd,
> stdin=wav_pipe)
> except WindowsError as exc:
> log_windows_error(exc, queue[position].nero_aac_cmd, 'critical')
> break
> finally:
> if queue[position].vol != 1:
> sox_proc.stdout.close()
> else:
> ffmpeg_proc.stdout.close()
> ffmpeg_proc.wait()
> if queue[position].vol != 1:
> sox_proc.wait()
> nero_aac_proc.wait()
I can't figure out what I changed since the last time I tried and
failed, though; I only ran it again after directing the stderr of FFmpeg
and SoX to actual files to see if they could gives me any clues.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to save a email message?

2011-07-02 Thread Steven D'Aprano
TheSaint wrote:

> Hello,
> I'm trying to gather some mail and save it. I don't get why it isn't saved
> as expected.

Short answer: you need to seek the fp file object back to the start of the
file by calling fp.seek(0). Otherwise, when you add it to the mail box, if
gets EOF immediately and nothing gets added.

More comments below:


> ==
> 
 import poplib, socket, sys
 from configparser import Error as ProtocolError
 args= sys.argv[1:] # this is fake but is here as example


It makes it very hard for us to run your code when you paste the interactive
session. For small snippets, it's okay to just post the interactive
session, but for more substantial code, it is best to past the function
definition ready for us to copy and paste:

def foo():
pass

>>> foo("arg")
>>>



 def Pop3_access(*args):
'''Accessing a pop server, doing a function and return a result'''
func= args[0]; args= args[1:]

Why don't you declare func as a named argument? 

def Pop3_access(func, *args):


try:
   pop= poplib.POP3(srv_info[0])
   pop.user(srv_info[1])
   pop.pass_(srv_info[2])
except (poplib.error_proto):
   raise ProtocolError
except (socket.timeout,socket.gaierror):
   try: pop.quit()
   except NameError: pass # it wasn't started
   return
result= func(pop, args)
pop.quit()
return result
> 
 def func(pop, N):
> ...return pop.retr(N)
> ...
 msg= Pop3_access(func, 4)
 from io import BytesIO as B
 fp= B()
 for l in msg[1]:
> ...fp.write(l)
> ...fp.write('\n'.encode())
> ...
> 34
> 1
> 50
> 1
[...]


For those wondering, as I was, what all these numbers are, the
BytesIO.write() method returns the number of bytes written. 

At this point, fp is a file-like object containing a number of bytes, but
the file pointer is at the end of the file, so when you read from it, it
immediately gets EOF (i.e. empty). 

>>> from io import BytesIO as B
>>> x = B()
>>> x.write(bytes("hello", 'ascii'))
5
>>> x.read()
b''

But if you seek back to the beginning:

>>> x.seek(0)
0
>>> x.read()
b'hello'



 from mailbox import mbox as Mbx

*raises eyebrow*

Do you need to rename mbox? You don't even save a keypress:
shift-m b x and m b o x both take 4 keypresses.


-- 
Steven

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


Re: Nested/Sub Extensions in Python

2011-07-02 Thread H Linux
On Jul 2, 3:46 am, Corey Richardson  wrote:
> Excerpts from H Linux's message of Fri Jul 01 16:02:15 -0400 2011:
>
> > Dear all,
>
> > I am currently fighting with a problem writing a set of Python
> > extensions in C.
>
> If you haven't seen it yet, Cython is a *very* nice tool for writing
> C extensions.http://cython.org/
Thanks for the tip, I'll have a look. Still fighting with plain python
though...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested/Sub Extensions in Python

2011-07-02 Thread H Linux
On Jul 2, 2:28 am, Carl Banks  wrote:
> On Friday, July 1, 2011 1:02:15 PM UTC-7, H Linux wrote:
> > Once I try to nest this, I cannot get the module to load anymore:
> > >import smt.bar
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > ImportError: No module named bar
>
> [snip]
>
> > PyMODINIT_FUNC
> > initbar(void)
> > {
> >    Py_InitModule("smt.bar", bar_methods);
> > }
>
> This should be: Py_InitModule("bar", bar_methods);
> That's probably it; other than that, it looks like you did everything right.
Thanks for your help, but I actually tried both ways. This does not
seem to be the problem, as it fails both ways with identical error
message.

> What does the installed file layout look like after running distutils setup?
Tree output is:
/usr/local/lib/python2.6/dist-packages/
├── foo.so
├── smt
│   ├── bar.so
│   ├── __init__.py
│   └── __init__.pyc
└── smt-0.1.egg-info

Just in case anyone is willing to have a look, here is a link to the
complete module as built with:
python setup.py sdist:
https://docs.google.com/leaf?id=0Byt62fSE5VC5NTgxOTFkYzQtNzI3NC00OTUzLWI1NzMtNmJjN2E0ZTViZTJi&hl=en_US

If anyone has any other ideas how to get it to work, thanks in
advance...
Hartwig


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


Re: An ODBC interface for Python 3?

2011-07-02 Thread Roger Upole
kozmikyak wrote:
> Does anyone here have a Python 3 environment that can access MSSQL
> using SQLAlchemy, running on a Windows 7 box?  If so, I would like
> some assistance making it happen.
>
> The last post on this was mid-2010.  It was mentioned that pyodbc had
> a Python 3 branch.  I've been unable to get it compiled and working on
> Windows 7 32-bit or 64-bit, even after applying patches mentioned in
> one of the project's tracking issues.
>
> Right now anyone forced to support Windows clients, Microsoft SQL, and
> SQLAlchemy has no option if wanting to use Python 3.2.  Neither
> pymssql or pyodbc compiles out-of-the-box for Python 3.2.  ceODBC
> compiles and runs, but SQLAlchemy project has stated that it has no
> desire to write yet another dialect supporting ceODBC for MSSQL.
>
> I'm not mentioning this just to complain; I'm just stating it out in
> the open so that it's known.  Indeed, even if one doesn't want to use
> MSSQL, the only free ODBC interface I know of that works on Python 3
> is ceODBC, and it is not supported by other modules such as
> SQLAlchemy.
>
> I'm wondering how I could best make something like this happen.  I've
> written to the SQLAlchemy and pyodbc projects.  I have average Python
> programming skills and have a Windows Python environment with C
> compiler installed; perhaps if the authors respond I can assist.
>
> If someone else has already figured out how to make this happen,
> please let me know.

Pywin32 has an odbc module that works with Python 3.2.

Roger



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


Re: How to save a email message?

2011-07-02 Thread TheSaint
Steven D'Aprano wrote:

Thank you very much.

> But if you seek back to the beginning:
> 
 x.seek(0)
> 0
 x.read()
> b'hello'
> 

Found the matter and *is* working
I discover another problem:
one message contains also a different encoding, but mostly it is not 
possible to represent that writing on the normale console output.

> 
> from mailbox import mbox as Mbx
> 
> raises eyebrow
> 
> Do you need to rename mbox? You don't even save a keypress:
> shift-m b x and m b o x both take 4 keypresses.

You stroke a right point :D
I could just use its own name

The code was not exactly run from the python shell. I was trying to make a 
*complete* picture from my module. In fact there aren't the arguments to 
access the pop server.
I'd like to mention that I've looked into the output file, which shows only 
"From MAILER DEAMON" + date of the action, but no message at all.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is the Usenet to mailing list gateway borked?

2011-07-02 Thread Thomas 'PointedEars' Lahn
TP wrote:

> Thomas 'PointedEars' Lahn wrote:
>> [Why are threads broken in the newsgroup?]
> 
> Not sure if this is relevant. I use mail.google.com to follow mailing
> lists and a large proportion of python-list traffic ends up in my
> gmail spam folder for some reason?

Your e-mail problems are unrelated to what happens in the newsgroup,
the fact aside that you are posting more text than necessary.



-- 
PointedEars

Bitte keine Kopien per E-Mail. / Please do not Cc: me.
-- 
http://mail.python.org/mailman/listinfo/python-list


How does CO_FUTURE_DIVISION compiler flag get propagated?

2011-07-02 Thread Terry
I've built a Python app for the iPhone, http://www.sabonrai.com/PythonMath/.

Like embedding Python in another app, it uses PyRun_SimpleString() to
execute commands entered by the user. For evaluating expressions, it
uses PyEval_EvalCode() with the dictionary from the __main__ module.

Future division ("from __future__ import division") works within
scripts executed by import or execfile(). However, it does not work
when entered interactively in the interpreter like this:

>>> from __future__ import division
>>> a=2/3

You get classic (integer) division, but if you enter it as follows,
you get future (float) division.

>>> from __future__ import division;a=2/3

It appears that the CO_FUTURE_DIVISION compiler flag is not being
retained in the interpreter so that later commands get compiled
without that flag.

I found a hint in
http://groups.google.com/group/comp.lang.python/browse_thread/thread/13a90a9f6eb96c73/960e47f572a59711?lnk=gst&q=co_future_division#960e47f572a59711,
but I don't see that PyRun_SimpleStringFlags returns the flags it
uses. I guess I could watch for the user to enter the import command
but that's really brittle.

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


Why won't this decorator work?

2011-07-02 Thread John Salerno
I thought I had finally grasped decorators, but the error I'm getting
('str' type is not callable) is confusing me. Here is my code. Also,
the commented sentence is from the Python docs, which says it doesn't
even need to be callable, if that matters. I also commented out a few
things in the move method. They were just to see if it would work, but
those lines raised even more errors!

import random

#space = 0

def move(roll):
#global space
#   space += roll
return 'You moved to space {0}.'.format(roll)

@move
def roll_die():
return random.randint(1, 6)

# The return value of the decorator need not be callable
# roll_die = move(roll_die)



I tried running the command "roll_die()" and I get the error message.

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


Re: Why won't this decorator work?

2011-07-02 Thread MRAB

On 02/07/2011 17:56, John Salerno wrote:

I thought I had finally grasped decorators, but the error I'm getting
('str' type is not callable) is confusing me. Here is my code. Also,
the commented sentence is from the Python docs, which says it doesn't
even need to be callable, if that matters. I also commented out a few
things in the move method. They were just to see if it would work, but
those lines raised even more errors!

import random

#space = 0

def move(roll):
#global space
#   space += roll
 return 'You moved to space {0}.'.format(roll)

@move
def roll_die():
 return random.randint(1, 6)

# The return value of the decorator need not be callable
# roll_die = move(roll_die)



I tried running the command "roll_die()" and I get the error message.

Thanks.


A decorator should return a callable.

This:

@move
def roll_die():
return random.randint(1, 6)

is equivalent to this:

def roll_die():
return random.randint(1, 6)

roll_die = move(roll_die)

You should be defining a function (a callable) and then passing it to a
decorator which returns a callable.

As it is, you're defining a function and then passing it to a decorator
which is returning a string. Strings aren't callable.
--
http://mail.python.org/mailman/listinfo/python-list


Re: poll of filesystem

2011-07-02 Thread Nobody
On Sat, 02 Jul 2011 11:40:46 +0200, Belisko Marek wrote:

> just want to use poll method to get data from /proc file system. Use
> simple code for it. Problem is it seems poll return POLLIN flag but
> when I try to read data it's always empty. Could be a problem changes
> are so fast that print can't print it?

poll() doesn't work for files; they are always readable. It's meant for
pipes, sockets and character devices (ttys, etc). If you're looking for a
way to find out when a file has changed, there isn't one (Linux has
inotify, but that isn't portable and it doesn't work with /proc).

The reason why fd.read() doesn't return any data after the first call is
that you're already at EOF; you need to reset the file position with
fd.seek(0) to read more data (however: for /proc, I would recommend
closing the file and reopening it).

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


Re: Does anyone know of a python tapi module

2011-07-02 Thread Alister Ware
On Fri, 01 Jul 2011 14:28:13 -1000, Werner Thie wrote:

> On 7/1/11 11:15 AM, Alister Ware wrote:
>> The subject probably say is all but to elaborate.
>>
>> I am looking for a way to communicate with a tapi driver for a PBX so I
>> can experiment with creating some CTI (Computer Telephony Integration)
>> software.
>>
>>
> I used TAPI since its inception for quite a few projects, but am not
> aware of anything pythonic. Attempting to cough up an interface layer I
> would resort to using Chris Sells tfx wrapper fro TAPI, which helps a
> lot keeping things in check and becoming overly complex.
> 
> HTH, Werner
> 
> http://books.google.com/books?id=3M_mIvtdGqUC&pg=PA82&lpg=PA82&dq=chris
+sell+tfx&source=bl&ots=5UhAxbFTym&sig=7hRn0oUbyZsm_yyDvASKD-
AT1jo&hl=en&ei=w2UOTsPlBJOisAP57JyrDg&sa=X&oi=book_result&ct=result&resnum=1&ved=0CBkQ6AEwAA

thanks for taking the time to look
Unfortunately I only have a nodding acquaintance with C & don't want togo 
down that route.
looks like I will have to see if I can work something out using the ctypes 
module




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


Re: Why won't this decorator work?

2011-07-02 Thread John Salerno
On Jul 2, 12:33 pm, MRAB  wrote:
> On 02/07/2011 17:56, John Salerno wrote:
>
>
>
>
>
>
>
>
>
> > I thought I had finally grasped decorators, but the error I'm getting
> > ('str' type is not callable) is confusing me. Here is my code. Also,
> > the commented sentence is from the Python docs, which says it doesn't
> > even need to be callable, if that matters. I also commented out a few
> > things in the move method. They were just to see if it would work, but
> > those lines raised even more errors!
>
> > import random
>
> > #space = 0
>
> > def move(roll):
> > #    global space
> > #   space += roll
> >      return 'You moved to space {0}.'.format(roll)
>
> > @move
> > def roll_die():
> >      return random.randint(1, 6)
>
> > # The return value of the decorator need not be callable
> > # roll_die = move(roll_die)
>
> > I tried running the command "roll_die()" and I get the error message.
>
> > Thanks.
>
> A decorator should return a callable.
>
> This:
>
>      @move
>      def roll_die():
>          return random.randint(1, 6)
>
> is equivalent to this:
>
>      def roll_die():
>          return random.randint(1, 6)
>
>      roll_die = move(roll_die)
>
> You should be defining a function (a callable) and then passing it to a
> decorator which returns a callable.
>
> As it is, you're defining a function and then passing it to a decorator
> which is returning a string. Strings aren't callable.

But why does the documentation say "The return value of the decorator
need not be callable"? And why, if I remove the decorator and just
leave the two functions as if, does the call to move(roll_die()) work?
Isn't that what the decorator syntax is essentially doing?
-- 
http://mail.python.org/mailman/listinfo/python-list


need to extend this C code so that it initiates this python script (python C api)

2011-07-02 Thread aregee
hi i need help with extending this http://paste.pound-python.org/show/8918/
c code so that it can initiate this python script 
http://paste.pound-python.org/show/8917/
and export file path here..

btw I tried to run following python code :

#include  //changed this to python2.7/Python.h
didn't work the I changed it to Python.h
  // Error msg : fatal
error: Python.h : no file or directory compilation terminated
 //python-dev and
python2.7-dev is already installed.

void process_expression(char* filename,
int num,
char** exp)
{
FILE*   exp_file;

// Initialize a global variable for
// display of expression results
PyRun_SimpleString("x = 0");

// Open and execute the file of
// functions to be made available
// to user expressions
exp_file = fopen(filename, "r");
PyRun_SimpleFile(exp_file, exp);

// Iterate through the expressions
// and execute them
while(num--) {
PyRun_SimpleString(*exp++);
PyRun_SimpleString("print x");
}
}

int main(int argc, char** argv)
{
Py_Initialize();

if(argc != 3) {
printf("Usage: %s FILENAME EXPRESSION+\n");
return 1;
}
process_expression(argv[1], argc - 1, argv + 2);
return 0;
}


thanks
aregee
Ar
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why won't this decorator work?

2011-07-02 Thread Tim Chase

On 07/02/2011 01:08 PM, John Salerno wrote:

On Jul 2, 12:33 pm, MRAB  wrote:

  roll_die = move(roll_die)

You should be defining a function (a callable) and then passing it to a
decorator which returns a callable.


But why does the documentation say "The return value of the decorator
need not be callable"?


I must not be looking at the same documentation you are...could 
you provide a link? The only time I know of that the return value 
of a decorator need not be callable is if you want to totally 
break the syntax of the function. :-/



And why, if I remove the decorator and just leave the two
functions as if, does the call to move(roll_die()) work? Isn't
that what the decorator syntax is essentially doing?


Are you doing

  move(roll_die()) #call roll_die() and pass results to move()

or

  move(roll_die) # pass the function-object roll_die to move()

?  The decorator syntax is the equivalent of

  roll_die = move(roll_die)

-tkc



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


Re: Why won't this decorator work?

2011-07-02 Thread Ian Kelly
On Sat, Jul 2, 2011 at 12:08 PM, John Salerno  wrote:
> But why does the documentation say "The return value of the decorator
> need not be callable"?

Because the language does not enforce the restriction that the return
value should be a callable.  If it's not a callable, then the result
will just be that something non-callable is bound to the "roll_die"
name -- which could be useful, but is probably a bad idea in general.

> And why, if I remove the decorator and just
> leave the two functions as if, does the call to move(roll_die()) work?
> Isn't that what the decorator syntax is essentially doing?

No.  The decorator syntax is doing:

roll_die = move(roll_die)

If you then call roll_die, that is equivalent to "move(roll_die)()",
which is not the same thing as "move(roll_die())".

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


Re: Why won't this decorator work?

2011-07-02 Thread ChasBrown
On Jul 2, 11:08 am, John Salerno  wrote:
> On Jul 2, 12:33 pm, MRAB  wrote:
>
>
>
> > On 02/07/2011 17:56, John Salerno wrote:
>
> > > I thought I had finally grasped decorators, but the error I'm getting
> > > ('str' type is not callable) is confusing me.

> > > def move(roll):
> > > return 'You moved to space {0}.'.format(roll)



>
> > A decorator should return a callable.

Well, should typically return a callable, but there are exceptions...

>
> > This:
>
> >      @move
> >      def roll_die():
> >          return random.randint(1, 6)
>
> > is equivalent to this:
>
> >      def roll_die():
> >          return random.randint(1, 6)
>
> >      roll_die = move(roll_die)
>
> > You should be defining a function (a callable) and then passing it to a
> > decorator which returns a callable.
>
> > As it is, you're defining a function and then passing it to a decorator
> > which is returning a string. Strings aren't callable.
>
> But why does the documentation say "The return value of the decorator
> need not be callable"?

Well, because it need not be callable: i.e., if the return value is
not callable, that is perfectly legal. You very rarely want to return
something else, but an example of this is the @property decorator: it
returns a property object, which is not callable.

> And why, if I remove the decorator and just
> leave the two functions as if, does the call to move(roll_die()) work?
> Isn't that what the decorator syntax is essentially doing?

No; instead it's doing the similar looking but quite different

move(roll_die)()

As you wrote it, move(roll_die) returns the string 'You moved to space
.' which is not callable. You typically want
instead something like:

def move(roll):
# note that roll is a function, not a number
def wrapper():
result = roll()
print 'You moved to space {0}.'.format(result)
return result
return wrapper # which is a function

Now move returns a callable (the function 'wrapper') so move(roll_die)
is callable, and move(roll_die)() is legal.

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


Re: Why won't this decorator work?

2011-07-02 Thread ChasBrown
On Jul 2, 11:08 am, John Salerno  wrote:
> On Jul 2, 12:33 pm, MRAB  wrote:
>
>
>
> > On 02/07/2011 17:56, John Salerno wrote:
>
> > > I thought I had finally grasped decorators, but the error I'm getting
> > > ('str' type is not callable) is confusing me.

> > > def move(roll):
> > > return 'You moved to space {0}.'.format(roll)



>
> > A decorator should return a callable.

Well, should typically return a callable, but there are exceptions...

>
> > This:
>
> >      @move
> >      def roll_die():
> >          return random.randint(1, 6)
>
> > is equivalent to this:
>
> >      def roll_die():
> >          return random.randint(1, 6)
>
> >      roll_die = move(roll_die)
>
> > You should be defining a function (a callable) and then passing it to a
> > decorator which returns a callable.
>
> > As it is, you're defining a function and then passing it to a decorator
> > which is returning a string. Strings aren't callable.
>
> But why does the documentation say "The return value of the decorator
> need not be callable"?

Well, because it need not be callable: i.e., if the return value is
not callable, that is perfectly legal. You very rarely want to return
something else, but an example of this is the @property decorator: it
returns a property object, which is not callable.

> And why, if I remove the decorator and just
> leave the two functions as if, does the call to move(roll_die()) work?
> Isn't that what the decorator syntax is essentially doing?

No; instead it's doing the similar looking but quite different

move(roll_die)()

As you wrote it, move(roll_die) returns the string 'You moved to space
.' which is not callable. You typically want
instead something like:

def move(roll):
# note that roll is a function, not a number
def wrapper():
result = roll()
print 'You moved to space {0}.'.format(result)
return result
return wrapper # which is a function

Now move returns a callable (the function 'wrapper') so move(roll_die)
is callable, and move(roll_die)() is legal.

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


Re: Why won't this decorator work?

2011-07-02 Thread ChasBrown
On Jul 2, 11:08 am, John Salerno  wrote:
> On Jul 2, 12:33 pm, MRAB  wrote:
>
>
>
> > On 02/07/2011 17:56, John Salerno wrote:
>
> > > I thought I had finally grasped decorators, but the error I'm getting
> > > ('str' type is not callable) is confusing me.

> > > def move(roll):
> > > return 'You moved to space {0}.'.format(roll)



>
> > A decorator should return a callable.

Well, should typically return a callable, but there are exceptions...

>
> > This:
>
> >      @move
> >      def roll_die():
> >          return random.randint(1, 6)
>
> > is equivalent to this:
>
> >      def roll_die():
> >          return random.randint(1, 6)
>
> >      roll_die = move(roll_die)
>
> > You should be defining a function (a callable) and then passing it to a
> > decorator which returns a callable.
>
> > As it is, you're defining a function and then passing it to a decorator
> > which is returning a string. Strings aren't callable.
>
> But why does the documentation say "The return value of the decorator
> need not be callable"?

Well, because it need not be callable: i.e., if the return value is
not callable, that is perfectly legal. You very rarely want to return
something else, but an example of this is the @property decorator: it
returns a property object, which is not callable.

> And why, if I remove the decorator and just
> leave the two functions as if, does the call to move(roll_die()) work?
> Isn't that what the decorator syntax is essentially doing?

No; instead it's doing the similar looking but quite different

move(roll_die)()

As you wrote it, move(roll_die) returns the string 'You moved to space
.' which is not callable. You typically want
instead something like:

def move(roll):
# note that roll is a function, not a number
def wrapper():
result = roll()
print 'You moved to space {0}.'.format(result)
return result
return wrapper # which is a function

Now move returns a callable (the function 'wrapper') so move(roll_die)
is callable, and move(roll_die)() is legal.

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


Re: poll of filesystem

2011-07-02 Thread Dan Stromberg
On Sat, Jul 2, 2011 at 2:40 AM, Belisko Marek wrote:

> Hi,
>
> just want to use poll method to get data from /proc file system. Use
> simple code for it. Problem is it seems poll return POLLIN flag but
> when I try to read data it's always empty. Could be a problem changes
> are so fast that print can't print it?
>

If you're wanting to watch when a file grows, you probably should just read
in a loop.  Not that this is likely what you need.

If you're wanting to see when a file changes, you could detect mtime changes
with os.stat.  This isn't 100% precise, but it should be good enough for
most uses of loadavg.  Make sure to put a sleep in your loop, unless your
loop is busy with other things already.

Various non-portable solutions might be good ways to go for you, because
/proc/loadavg isn't portable anyway.  These include uevent, fanotify and
perhaps inotify (there was apparently some discussion of removing the
inotify /proc restriction a while back, not sure if anything happened with
that).  I'm not confident any or all of these will work, but if you're
concerned about efficiency, you should explore them.

If you don't care about efficiency much, the mtime thing is probably the way
to go - there's little question that should work:

python -c 'import os; print(os.stat("/proc/loadavg").st_mtime)'
-- 
http://mail.python.org/mailman/listinfo/python-list


from module import * using __import__?

2011-07-02 Thread Dan Stromberg
Is there a decent way of running "from  import *"?  Perhaps using
__import__?

Does it mean using the copy module or adding an element to globals()
somehow?

Yes, I think I do have a good use for this: importing either pure python or
cython versions of a module into a single namespace that can provide the
same interface (transparent to the caller), whether C extension modules are
viable in the current interpreter or not.  So you have a stub module that
provides one or the other, depending on availability and suitability.

Related bit: I want it to pylint smoothly despite being in a python package,
so I'd like to use normal import for the pure python, and __import__ (or
similar) for the cython - where the pure python and cython are automatically
generated from the same .m4 file, and the cython is attempted first, falling
back on the pure python if there's an ImportError.  I'd like to believe
pylint is going to check the pure python this way, and ignore the fact that
it often cannot import the cython.

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


Re: How does CO_FUTURE_DIVISION compiler flag get propagated?

2011-07-02 Thread Hrvoje Niksic
Terry  writes:

> Future division ("from __future__ import division") works within
> scripts executed by import or execfile(). However, it does not work
> when entered interactively in the interpreter like this:
>
 from __future__ import division
 a=2/3

Are you referring to the interactive interpreter normally invoked by
just running "python"?  That seems to work for me:

Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/3
0
>>> from __future__ import division
>>> 2/3
0.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why won't this decorator work?

2011-07-02 Thread John Salerno
On Jul 2, 1:45 pm, Tim Chase  wrote:

> I must not be looking at the same documentation you are...could
> you provide a link? The only time I know of that the return value
> of a decorator need not be callable is if you want to totally
> break the syntax of the function. :-/

http://docs.python.org/py3k/whatsnew/2.4.html?highlight=decorator

Sort of around the middle of the PEP 318 section.

But I think I understand now. I was thinking the decorator I made was
creating move(roll_die()), which I see now that it is not. Perhaps a
decorator isn't what I need in my case, although it seems like it
might be.

Basically what I want to do is this: I first to need to roll a die to
get a random number, then pass that number to the move method of a
Player class. Can this be done with a decorator, or is it better just
to do it like move(roll_die()) and be done with it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested/Sub Extensions in Python

2011-07-02 Thread Carl Banks
On Saturday, July 2, 2011 6:35:19 AM UTC-7, H Linux wrote:
> On Jul 2, 2:28 am, Carl Banks 
>  wrote:
> > On Friday, July 1, 2011 1:02:15 PM UTC-7, H Linux wrote:
> > > Once I try to nest this, I cannot get the module to load anymore:
> > > >import smt.bar
> > > Traceback (most recent call last):
> > >   File "", line 1, in 
> > > ImportError: No module named bar
> >
> > [snip]
> >
> > > PyMODINIT_FUNC
> > > initbar(void)
> > > {
> > >    Py_InitModule("smt.bar", bar_methods);
> > > }
> >
> > This should be: Py_InitModule("bar", bar_methods);
> > That's probably it; other than that, it looks like you did everything right.
> Thanks for your help, but I actually tried both ways. This does not
> seem to be the problem, as it fails both ways with identical error
> message.

Correct, I misspoke.  The problem would be if the initbar function name was 
misspelled.


> > What does the installed file layout look like after running distutils setup?
> Tree output is:
> /usr/local/lib/python2.6/dist-packages/
> ├── foo.so
> ├── smt
> │   ├── bar.so
> │   ├── __init__.py
> │   └── __init__.pyc
> └── smt-0.1.egg-info
> 
> Just in case anyone is willing to have a look, here is a link to the
> complete module as built with:
> python setup.py sdist:
> https://docs.google.com/leaf?id=0Byt62fSE5VC5NTgxOTFkYzQtNzI3NC00OTUzLWI1NzMtNmJjN2E0ZTViZTJi&hl=en_US
> 
> If anyone has any other ideas how to get it to work, thanks in
> advance...

I got and built the package, and it imported smt.bar just fine for me.

So my advice would be to rename all the modules.  My guess is that there is a 
conflict for smt and Python is importing some other module or package.  Is 
there a file called smt.py in your working directory?  Try doing this:

import smt
print smt.__file__

And see if it prints at the location where your smt module is installed.  If 
not, you have a conflict.

And if that is the problem, in the future be more careful to keep your module 
namespace clean.  Choose good, distinct names for modules and packages to 
lessen the risk of conflict.


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


Inexplicable behavior in simple example of a set in a class

2011-07-02 Thread Saqib Ali


I have written two EXTREMELY simple python classes. One class
(myClass1) contains a data attribute (myNum) that contains an integer.
The other class (myClass2) contains a data attribute (mySet) that
contains a set.

I instantiate 2 instances of myClass1 (a & b). I then change the value
of a.myNum. It works as expected.

Then I instantiate 2 instances of myClass2 (c & d). I then change the
value of c.mySet. Bizarrely changing the value of c.mySet also affects
the value of d.mySet which I haven't touched at all!?!?! Can someone
explain this very strange behavior to me? I can't understand it for
the life of me.

Please see below the source code as well as the output.


-- SOURCE CODE --
import sets

class myClass1:

myNum = 9

def clearNum(self):
self.myNum = 0

def __str__(self):
  return str(self.myNum)

class myClass2:

mySet = sets.Set(range(1,10))

def clearSet(self):
self.mySet.clear()

def __str__(self):
  return str(len(self.mySet))

if __name__ == "__main__":

# Experiment 1. Modifying values of member integers in two
different instances of a class
# Works as expected.
a = myClass1()
b = myClass1()
print "a = %s" % str(a)
print "b = %s" % str(b)
print "a.clearNum()"
a.clearNum()
print "a = %s" % str(a)
print "b = %s\n\n\n" % str(b)



# Experiment 2. Modifying values of member sets in two different
instances of a class
# Fails Unexplicably. d is not being modified. Yet calling
c.clearSet() seems to change d.mySet's value
c = myClass2()
d = myClass2()
print "c = %s" % str(c)
print "d = %s" % str(d)
print "c.clearSet()"
c.clearSet()
print "c = %s" % str(c)
print "d = %s" % str(d)




-- OUTPUT --
> python.exe myProg.py

a = 9
b = 9
a.clearNum()
a = 0
b = 9



c = 9
d = 9
c.clearSet()
c = 0
d = 0
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inexplicable behavior in simple example of a set in a class

2011-07-02 Thread Chris Rebert
On Sat, Jul 2, 2011 at 2:59 PM, Saqib Ali  wrote:

> Then I instantiate 2 instances of myClass2 (c & d). I then change the
> value of c.mySet. Bizarrely changing the value of c.mySet also affects
> the value of d.mySet which I haven't touched at all!?!?! Can someone
> explain this very strange behavior to me? I can't understand it for
> the life of me.

> class myClass2:
>
>    mySet = sets.Set(range(1,10))
>
>    def clearSet(self):
>        self.mySet.clear()
>
>    def __str__(self):
>          return str(len(self.mySet))

Please read a tutorial on object-oriented programming in Python. The
official one is pretty good:
http://docs.python.org/tutorial/classes.html
If you do, you'll find out that your class (as written) has mySet as a
class (Java lingo: static) variable, *not* an instance variable; thus,
it is shared by all instances of the class, and hence the behavior you
observed. Instance variables are properly created in the __init__()
initializer method, *not* directly in the class body.

Your class would be correctly rewritten as:

class MyClass2(object):
def __init__(self):
self.mySet = sets.Set(range(1,10))

def clearSet(self):
# ...rest same as before...

Cheers,
Chris
--
http://rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inexplicable behavior in simple example of a set in a class

2011-07-02 Thread Peter Otten
Saqib Ali wrote:

> 
> 
> I have written two EXTREMELY simple python classes. One class
> (myClass1) contains a data attribute (myNum) that contains an integer.
> The other class (myClass2) contains a data attribute (mySet) that
> contains a set.
> 
> I instantiate 2 instances of myClass1 (a & b). I then change the value
> of a.myNum. It works as expected.

self.value = new_value

sets the attribute to a new value while

self.value.modifying_method()

keeps the old value (the object with the same id(object)), but changes the 
state of that old object. All variables bound to that object will "see" that 
internal change of state. As integers are "immutable" objects whose state 
cannot be changed you'll never observe the behaviour described below with 
them.

> Then I instantiate 2 instances of myClass2 (c & d). I then change the
> value of c.mySet. Bizarrely changing the value of c.mySet also affects
> the value of d.mySet which I haven't touched at all!?!?! Can someone
> explain this very strange behavior to me? I can't understand it for
> the life of me.

What you access as c.mySet or d.mySet is really myClass2.mySet, i. e. a 
class attribute and not an instance attribute. If you want a set per 
instance you have to create it in the __init__() method:

>>> class MyClass:
... def __init__(self):
... self.my_set = set(range(10))
... def clear_set(self):
... self.my_set.clear()
...
>>> a = MyClass()
>>> b = MyClass()
>>> a.my_set.add(42)
>>> a.my_set, b.my_set
(set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 42]), set([0, 1, 2, 3, 4, 5, 6, 7, 8, 
9]))
>>> b.clear_set()
>>> a.my_set, b.my_set
(set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 42]), set([]))

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


Re: Inexplicable behavior in simple example of a set in a class

2011-07-02 Thread Saqib Ali
> Instance variables are properly created in the __init__()
> initializer method, *not* directly in the class body.
>
> Your class would be correctly rewritten as:
>
> class MyClass2(object):
>     def __init__(self):
>         self.mySet = sets.Set(range(1,10))
>
>     def clearSet(self):
> # ...rest same as before...


Thanks Chris. That was certainly very helpful!!

So just out of curiosity, why does it work as I had expected when the
member contains an integer, but not when the member contains a set?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why won't this decorator work?

2011-07-02 Thread Ben Finney
John Salerno  writes:

> Basically what I want to do is this: I first to need to roll a die to
> get a random number, then pass that number to the move method of a
> Player class. Can this be done with a decorator, or is it better just
> to do it like move(roll_die()) and be done with it?

If what you want can be expressed with ‘player.move(roll_die())’, I'm
confused as to why you think decorators would help.


A decorator is syntactic sugar for something quite different::

@foo(spam, eggs)
@bar
def baz(beans):
""" … """

is equivalent to::

def baz(beans):
""" … """

baz = foo(spam, eggs)(bar(baz))

except in the first instance, the function defined never gets bound to
the name ‘baz’ even temporarily.

* The function ‘baz’ is defined, resulting in a function object. (In the
  first example, it is never bound to the name ‘baz’.)

* The expression ‘bar’ is evaluated, and the result (probably a function
  named ‘bar’) is called with the function object defined as ‘baz’; the
  return value should be a new function.

* The expression ‘foo(spam, eggs)’ is evaluated, and the result (the
  return value from that function call) is itself called, passing the
  return value from the call to ‘bar’.

* Finally, the return value from all of that is bound to the name ‘baz’.

Note that, in both ways of writing that, ‘baz’ is never called, but
instead the function object ‘baz’ is used as a parameter. Also, the
original function defined as ‘baz’ is no longer accessible.


That seems quite unrelated to your stated requirements. If you're not
accustomed to passing function objects around as data, that can be
difficult to wrap your head around; if you didn't know you needed it,
you probably don't in this case.

-- 
 \ “Jealousy: The theory that some other fellow has just as little |
  `\ taste.” —Henry L. Mencken |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: poll of filesystem

2011-07-02 Thread Tim Roberts
Belisko Marek  wrote:
>
>just want to use poll method to get data from /proc file system. Use
>simple code for it. Problem is it seems poll return POLLIN flag but
>when I try to read data it's always empty. Could be a problem changes
>are so fast that print can't print it?

Poll doesn't make sense here.  The data in /proc/loadavg data is not text
data that gets updated periodically.  There is no file on disk somewhere
called /proc/loadavg.  Instead, reading /proc/loadavg causes a call into a
kernel driver, and reads data directly from variables stored in the kernel.
The data is ALWAYS available.

If you want the data once a second, just do it the easy way:

import time
while True:
print open('/proc/loadavg').read()
time.sleep(1)
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
Hello fellow programmers, scripters, hackers, and debutantes.

I have cross posted this thread to three groups that i believe need to
unite under the flag of unity for the benefit of all. Because when we
unite we not only help ourselves, we promote freedom. In the next few
paragraphs i will expose the source of this problem and propose a
viable solution for how WE can solve the problem!

It saddens me when i see API's that don't include at least three
language choices. No *one* language is going to please the masses. I
understand *WHY* this happens however it should never, *EVER* happen
and i cannot lay blame solely on application developers because "we"
have failed to provide them NOT ONLY with a unifying API model, but
also our  respective "plugin" interfaces to that unifying model.

Yes folks  "WE" are to blame for this dilemma. Who is "we" exactly?
"We" is any language community who's language exhibits the traits of
an API scripting language. For me that group includes (at the minimum)
Python, Ruby, Basic, Perl, JavaScript, and whoever else wants to be
part of this group.

Everyone knows that no one language can solve all problems. And
likewise everyone knows that even when two languages are similar (in
few ways, or in many ways) people are always going to draw lines in
the sand and prefer to use one language over another. It is natural to
simply ones working environment. How many of you folks speak English
on Mondays and Mandarin on Tuesdays and Spanish on Wednesdays and
French on Thursdays and Bulgarian on Fridays and Pig Latin on
Saturdays and Orc on Sundays? Anyone? Why i am not surprised!

But we do this very same asinine thing on a daily basis whist jumping
through the productivity limiting hoops. The stench of which rises up
from every community of language developers in the world. We have not
only created a mutual cess pool of laziness and selfishness , we are
wallowing and rooting around in it completely oblivious of our
collectively bombastic stupidity.

So i ask yous, why should we continue to propagate hateful feelings,
or have some among us feel left out because their favorite language is
not included as an alternative in the API they are using at the time?
Why should i need to switch back and forth between multiple languages,
multiple syntaxes, multiple editors, multiple help files, multiple API
help files, and suffer multiple headaches just because the status quo
is to be selfish and not care about the greater "Programming
Community".

"Community". Hmm, now that is a word that can be applied in many
dimensions. The "Python Community" is a community that inherits from
the "Programming Community"... as is the "Ruby Community" and the
"JavaScript Community" and so on and so forth. We are naturally good
at taking care of our immediate community but for the community once
removed we are failing miserably! And this community is the most
important community of all! When we damage the programming community
we damage ourselves and everyone else!

[Thought Exercise] Just imagine for a second if automobiles where
engineered the way programming languages are currently engineered. But
wait! Before we jump into insightful analyolgies we must first
understand why the automobile is such a versatile feat of engineering.
The automobile -- no matter how large or small, not matter if truck or
car or motorcycle or moped-- is designed to interface with a system...
the "highway" system.  The user of an automobile is never restricted
from driving his favorite car. He is always happy because he is free.
Free to choose and free to be HOWEVER NOT THE CASE WITH APIs!

For API's we have just tossed freedom to the wind fro the sake of
selfishness. We would have multiple language developers creating
languages without any regard for a language independent system to plug
said language into. But i am here to tell you that we can be different
with our language style and still promote the freedom to choose. The
tool is NOT Ruby or Python or whatever. The tool is software which
manifests itself as "ones" and "zeros". Layers of abstraction that all
compile to the same base units... 1's and 0's.  Languages are
abstractions of ones and zeros. Languages are NOT tools. Therefore we
all have a vested interest in a unifying API.

Well some would say... " it is up to the developer of an application
what language they choose"... and this is true. But i say they can
choose to allow the users to choose thereby maintaining not only a
happier user base, but a more productive one as well.

When are we going to see the light and start unifying our collective
differences into a singular plug and play API and allowing the user of
"our" abstraction language, "our" for loop, or "our" version of
stdout.write the ultimate of all choices...  the choice of FREEDOM.

for danish inspirations see:

http://wiki.services.openoffice.org/wiki/Uno

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


Re: Inexplicable behavior in simple example of a set in a class

2011-07-02 Thread Chris Rebert
On Sat, Jul 2, 2011 at 3:23 PM, Saqib Ali  wrote:
>> Instance variables are properly created in the __init__()
>> initializer method, *not* directly in the class body.
>>
>> Your class would be correctly rewritten as:
>>
>> class MyClass2(object):
>>     def __init__(self):
>>         self.mySet = sets.Set(range(1,10))
>>
>>     def clearSet(self):
>> # ...rest same as before...
>
>
> Thanks Chris. That was certainly very helpful!!
>
> So just out of curiosity, why does it work as I had expected when the
> member contains an integer, but not when the member contains a set?

To explain that, one must first understand that name lookup on an
object looks in the following places, in order:
1. the instance itself
2. the instance's class
3. the instance's superclasses

So, if we have:

class Foo(object):
bar = 7
foo_inst = Foo()

then both `foo_inst.bar` and `Foo.bar` refer to the same value.

However, if we then do:

foo_inst.bar = 42

then we'll have:

foo_inst.bar == 42 and Foo.bar == 7


Now back to your actual question. In clearNum(), you do:
self.myNum = 0
which creates a *new* instance variable that shadows the class
variable of the same name, like in my example. If you check, you'll
indeed see that myClass1.myNum is still 9 after calling clearNum().

By contrast, in clearSet() you do:
self.mySet.clear()
which just mutates the existing Set object in-place. No new variable
is created, and mySet is still a class variable and thus shared by all
instances.

Further reading:
http://effbot.org/zone/python-objects.htm
http://effbot.org/zone/call-by-object.htm

Cheers,
Chris
--
http://rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread Chris Angelico
I know I shouldn't get sucked into responding to a rant, but it's like
a black hole - it's inevitable you'll cross the horizon...

On Sun, Jul 3, 2011 at 8:59 AM, rantingrick  wrote:
> It saddens me when i see API's that don't include at least three
> language choices. No *one* language is going to please the masses.

This is pretty much the entire argument, everything else is exposition.

It takes work to suit your API to a different language. Let's take GNU
Aspell as an example; it's a good tool, and the ability to spell-check
something is sufficiently general that many programs can make use of
it.

Its list of "supported languages" isn't what we're looking for, though
(it lists Afrikaans, Greek, English, etc); from what I see, it
supports only C++. Should the Aspell team offer bindings for every
known language? In your post, you recommend supporting a minimum of
three. Which three? Why?

I'm a great fan of an obscure language named Pike. Do I expect Aspell
to be available for Pike? No, and I wouldn't even if your
three-language rule were followed. So how can I implement a
spellchecker in my code? By writing glue. I'll write a module that
exposes the C++ API to Pike. (This is actually a real example. I ended
up writing my aspell hook to run as a separate process for isolation's
sake, but it comes to the same thing.)

Unless the world consolidates into a smaller number of languages, this
is always going to be the case. You want the freedom to choose your
language and your API separately? You HAVE that freedom - you just
have to write your own glue. Glue-writing is a skill in the same way
that UI-building is; learn to do it well and you can do it quickly.
There's no need to demand that other people write your glue for you,
because chances are they won't do as good a job as an expert in the
language.

C or C++ bindings will cover most languages.

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
On Jul 2, 6:38 pm, Chris Angelico  wrote:

[... snip expositions...]

> C or C++ bindings will cover most languages.
>
> Chris Angelico

This is pretty much the entire argument, everything else is
exposition.

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


Re: How does CO_FUTURE_DIVISION compiler flag get propagated?

2011-07-02 Thread Terry
On Jul 2, 3:55 pm, Hrvoje Niksic  wrote:
> Terry  writes:
> > Future division ("from __future__ import division") works within
> > scripts executed by import or execfile(). However, it does not work
> > when entered interactively in the interpreter like this:
>
>  from __future__ import division
>  a=2/3
>
> Are you referring to the interactive interpreter normally invoked by
> just running "python"?  That seems to work for me:
>
> Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
> [GCC 4.5.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> 2/3
> 0
> >>> from __future__ import division
> >>> 2/3
>
> 0.

Yes, that works for me on my Mac. The problem I'm having is in a
Python interpreter that I built for the iPhone. It uses
PyRun_SimpleString() to execute user entered commands. After you
import future division, it does not seem to remember it on subsequent
commands.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
On Jul 2, 6:38 pm, Chris Angelico  wrote:
[...]
> It takes work to suit your API to a different language. Let's take GNU
> Aspell as an example; [...] Should the Aspell team offer bindings for every
> known language? In your post, you recommend supporting a minimum of
> three. Which three? Why?

No. Aspell should offer bindings for THE "Unity API" and the
respective "abstraction communities" are then responsible for
maintaining a plugin for their "abstraction" into THE Unity API.

> I'm a great fan of an obscure language named Pike. Do I expect Aspell
> to be available for Pike?

You should expect this. However if it is not available you cannot
blame Aspell for that! No, you MUST blame the pike community.

But first we have to blame EVERYONE because the unity API does not
exist... not yet! Or at least the mindset for it does not exists.

> No, and I wouldn't even if your
> three-language rule were followed.

My rule is for "unlimited unity" not "limited numbers".

> So how can I implement a
> spellchecker in my code? By writing glue. I'll write a module that
> exposes the C++ API to Pike. (This is actually a real example. I ended
> up writing my aspell hook to run as a separate process for isolation's
> sake, but it comes to the same thing.)

Yeah and they have a name for that... "reinventing the wheel". An end
user should NEVER EVER have to write glue code so their "abstraction
of choice" can be used to to script an API. That's like expecting
automobile drivers to build a car from a hunk of iron ore every time!
No, we have car manufactures who specialize in building cars. However
the respective programming language communities are all oblivious to
the greater picture. An iteration is an iteration whether you use the
"for x in iterable: x.blah()" or the "iterable.each{|x| x.blah}" or
WHATEVER syntax you choose to use. It all boils down to the same 1's
and 0's. Can't you see how our own sense of selfish pride is defeating
productivity and discovery? Can't you see?

It's fine to speak French, or Japanese, or English if you want. But
eventually we will need a unifying natural language and likewise a
unifying programming language.

[Note to community] Actually from now on i want everyone to stop using
the words programming and language together. Instead of "X programming
language" i want to you say "X abstraction layer".

Python programming language --> Python abstraction layer.
Ruby programming language --> Ruby abstraction layer.
X programming language --> X abstraction layer.

You see, we constantly refer to languages as tools, and this mindset
is lunacy! All languages compile to 1's and 0's. Languages are not
TOOLS they are all ABSTRACTIONS of a single virtual tool AND THAT TOOL
IS SOFTWARE!). So stop brainwashing yourselves and others with these
foolish descriptors! Begin to focus your mind on unity and
standardization. Then and only then can we combine our singular minds
into the hive mind.


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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread Chris Angelico
On Sun, Jul 3, 2011 at 10:21 AM, rantingrick  wrote:
> No. Aspell should offer bindings for THE "Unity API" and the
> respective "abstraction communities" are then responsible for
> maintaining a plugin for their "abstraction" into THE Unity API.
>

Your proposed "Unity API" (which I assume has nothing to do with Natty
Narwhal's preferred interface) already exists. It's the C language.
It's an abstraction layer between CPython, Pike, etc, and the
underlying hardware. The C standard library has a huge set of utility
functions like strcmp, malloc, and so on; by writing your code in C,
you simply enhance the C library. Language authors make use of this
enhanced C library to write functions to be called from that language.

And I don't *blame* the PIke community; since I'm a part of it, and
I'm quite probably the only part of it to need/want Aspell, I just
write the facilities I want.

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread Dan Stromberg
On Sat, Jul 2, 2011 at 5:21 PM, rantingrick  wrote:

> On Jul 2, 6:38 pm, Chris Angelico  wrote:
> [...]
> > It takes work to suit your API to a different language. Let's take GNU
> > Aspell as an example; [...] Should the Aspell team offer bindings for
> every
> > known language? In your post, you recommend supporting a minimum of
> > three. Which three? Why?
>
> No. Aspell should offer bindings for THE "Unity API" and the
> respective "abstraction communities" are then responsible for
> maintaining a plugin for their "abstraction" into THE Unity API.
>

Adding a new API is seldom the way to decrease the number of API's.  At
least, not without -=very=- centralized control over which API's get used.

I actually rather like it that no language has achieved the dominance today
that C once enjoyed, rightly or wrongly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Inexplicable behavior in simple example of a set in a class

2011-07-02 Thread Chris Angelico
On Sun, Jul 3, 2011 at 8:23 AM, Saqib Ali  wrote:
> So just out of curiosity, why does it work as I had expected when the
> member contains an integer, but not when the member contains a set?

It's not integer vs set; it's the difference between rebinding and
calling a method. It's nothing to do with object orientation; the same
happens with ordinary variables:

>>> a=b=1
>>> a,b
(1, 1)
>>> a=2
>>> a,b
(2, 1)

>>> c=d=[]
>>> c,d
({}, [])
>>> c.append("Test")
>>> c,d
(['Test'], ['Test'])

But:
>>> c=['Foobar']
>>> c,d
(['Foobar'], ['Test'])

When you do a=2 or c=['Foobar'], you're rebinding the name to a new
object. But c.append() changes that object, so it changes it
regardless of which name you look for it by.

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick

Take Pidgin[1] as an example. Pidgin is a universal chat client. It's
a glue between the many chat clients that exist... It's a monkey patch
for chat multiplicity but you get the idea. However the Unity API
cannot be a monkey patch. It must be a mutual undertaking from the
beginning. Don't you people understand? Multiplicity is undermining
our future evolution.

[Anecdote]
Once when i was a very young lad (long before computers were
mainstream) i became terribly troubled by the fact that every
generation must spend roughly a quarter of it's lifetime just catching
up to the knowledge of the last generation. This fact does not seem
very troublesome at first glance, but lets create a microcosm...
...what if you suffered from amnesia every
morning and you had to spend 1/4 of the day catching up to where you
were the day before? This would kill your productivity! But that is
not the point i am making here folks! <\back on track> The fact that
we constantly re-invent the wheel is a product of a very important
missing feature of most humans of which is devastating to our
evolution as intelligent agents.

[The Punchline]
Anyway, my solution to this collective "re-education" was the upload.
We could simply plug up, upload all former knowledge, and off we'd
go!

[The Knockout]
However when i shared my solution with someone [unnamed] he laughed
and said: "But that would take the challenge out of life. Nothing
remaining to learn if you can just download it"... aghast with horror
i just shook my head. This person had no imagination!

[The Moral]
Stop being sheep and start the revolution people! Stop being slaves to
multiplicity and be the master of the singularity. Our future (or lack
thereof) is in YOUR hands!

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


Re: Inexplicable behavior in simple example of a set in a class

2011-07-02 Thread Chris Rebert
On Sat, Jul 2, 2011 at 5:46 PM, Chris Angelico  wrote:
> On Sun, Jul 3, 2011 at 8:23 AM, Saqib Ali  wrote:
>> So just out of curiosity, why does it work as I had expected when the
>> member contains an integer, but not when the member contains a set?
>
> It's not integer vs set; it's the difference between rebinding and
> calling a method. It's nothing to do with object orientation; the same
> happens with ordinary variables:

 c=d=[]
 c,d
> ({}, [])

Nasty typo in your pseudo-interpreter-session there...

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread Tim Chase

On 07/02/2011 06:46 PM, rantingrick wrote:

On Jul 2, 6:38 pm, Chris Angelico  wrote:

It saddens me when i see API's that don't include at least three
language choices. No *one* language is going to please the masses.


C or C++ bindings will cover most languages.


This is pretty much the entire argument, everything else is
exposition.


So you've got 3 interfaces: C, C++, and for the die-hards, 
Assembly.  Sounds like you should be happy then ;-)


(what?  they weren't *your* top-3 language choices?)

-tkc


One API to rule them all,
One API to find them,
One API to bring them all
and in the darkness create bindings for them?



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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread Chris Angelico
On Sun, Jul 3, 2011 at 10:58 AM, rantingrick  wrote:
>
> Take Pidgin[1] as an example. Pidgin is a universal chat client. It's
> a glue between the many chat clients that exist... It's a monkey patch
> for chat multiplicity but you get the idea. However the Unity API
> cannot be a monkey patch. It must be a mutual undertaking from the
> beginning. Don't you people understand? Multiplicity is undermining
> our future evolution.

It's protocol glue, not programming code glue. There's a difference;
Pidgin replaces "chat client X", rather than piggybacking onto it.
Proliferation of code layers results in a performance penalty that
proliferation of chat clients doesn't. However, there is still a
parallel.

Any universal protocol will suffer either from complexity or
narrowness - some suffer from both. If every API has to go through
this Unity API, then either Unity will be as powerful and complex as C
with all its libraries, or it'll overly restrict things. That's why
Unity is really just C.

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


Re: Inexplicable behavior in simple example of a set in a class

2011-07-02 Thread Chris Angelico
On Sun, Jul 3, 2011 at 11:07 AM, Chris Rebert  wrote:
> c,d
>> ({}, [])
>
> Nasty typo in your pseudo-interpreter-session there...

Whoops! This is what I get for trying to be too smart!

>>> c,d
([], [])

Thanks for catching that, Chris. :)

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


web browsing short cut

2011-07-02 Thread Dustin Cheung
Hey guys,

I am new to python. I want to make a shortcut that opens my websites
and re-sizes them to  display on different areas on the screen. I looked
around but i had no luck. Is that possible with python? if so can someone
point to to the right direction? Here is what I came up with so far..

Thanks in advance,

--


import webbrowser

# The websites i want to open..
url1 = 'http://www.python.org/'
url2 = 'http://www.google.com/'
url3 = 'http://msn.com/'

# the path to ie
ie = webbrowser.get('c:\\program files\\internet explorer\\iexplore.exe')
ie.open(url1)
ie.open(url2)
ie.open(url3)




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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
On Jul 2, 8:12 pm, Chris Angelico  wrote:

> Any universal protocol will suffer either from complexity or
> narrowness - some suffer from both. If every API has to go through
> this Unity API, then either Unity will be as powerful and complex as C
> with all its libraries, or it'll overly restrict things. That's why
> Unity is really just C.

Well i never said we could not just use c of course. I'm trying to
lubricate the imagination here :).

However you have to convince the application devs of that. Most just
create bindings for a well known language like Python or Ruby and call
it a day. However some idiots go as far as writing their own mini
language (Audacity comes to mind!) and we cannot allow this to
happen!

The same problem exists in GUI's. Why the hell is there so many GUI
libraries? How many different label widgets do we need to re-invent?
It's ludicrous! Okay somebody might argue that we cannot just have one
because it would be too large. WHAT! Again imagination is the missing
link here. There is a simple solution... it's called "from GUI import
subset.x.y.z"!

I mean what is the point of having two languages with the exact same
syntax?

Ruby: print 'blah'
Python: print 'blah'

Ruby: for x in blah: blah_blah_blah
Python: for x in blah: blah_blah_blah

WHAT?

This multiplicity reminds me of a beginning CS student code:

def add(1,2):
return 1+2
def add(3,4):
return 3+4
def ...


Instead of:

def add(x, y);
return x+y

asinine!

Devs preach of code re-use but they propagate multiplicity in their
language design. Sadly we are still in the stone age of programming
and i don't know if i'll live long enough to see a real revolution.
People are waiting in breads lines all day but do not consider why?
(or they are too afraid to ask).

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread Chris Angelico
On Sun, Jul 3, 2011 at 11:43 AM, rantingrick  wrote:
> I mean what is the point of having two languages with the exact same
> syntax?
>
> Ruby: print 'blah'
> Python: print 'blah'
>
> Ruby: for x in blah: blah_blah_blah
> Python: for x in blah: blah_blah_blah
>
> WHAT?
>

What's the point of having fifty languages in which "x+y" is an
expression whose value is the sum of x and y? Let's ditch 'em all and
just use one language, since _obviously_ the languages have the exact
same syntax.

Common syntax is an aid to learning. It means you can transfer
knowledge from one language to another. It doesn't make either
useless.

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
> On Sat, Jul 2, 2011 at 7:37 PM, Dan Stromberg wrote:
>
> Adding a new API is seldom the way to decrease the number of API's.
> At least, not without -=very=- centralized control over which API's
> get used.
>
> I actually rather like it that no language has achieved the
> dominance today that C once enjoyed, rightly or wrongly.

You make a good point Dan! Like of most of my threads this one is
evolving into something deeper and more profound. Like i recently
pointed out in my last post we have many languages that are just
slightly different (and sometimes spitting images) of others. For
example Python and Ruby share some very close similarities. Of course
they share many differences also but the point is we are duplicating
too much methodology in our language designs.

You make the argument that C is really all you need. And i whole
hearty agree however you must also agree that there is a great need
for Python and Ruby type languages. Languages that are much more user
friendly than C and don't require memory management.

Remember, most API users are not always CS majors. C is not beyond the
scope of any normal functioning human being however it does require
not only a steeper learning curve but caution whilst wielding it. I
mean who wants a seg fault when scripting Open Office, or how about
writing a page of boilerplate for what amounts to a half page script?

For me the ideal situation we could have is a unity of all the high
level languages. Dump all the repeated syntax's and try to compile the
best of all into as few "scripting langages" as possible. Of we can do
it in one GREAT, if not three or so sounds about correct.

Then these "cream of the crop" could be integrated tightly with
extension writing. So that you could start at the scripting level and
move down as needed for speed and low level stuff when needed.

But we need the application devs to take part or the whole house of
cards comes tumbling down. And how do you motivate people to use a
certain API. Simplicity is one way, peer pressure is another, bulling
when necessarily can help. Whatever it takes because we all have a
vested interest in unity. We must start the ball rolling.Continuing to
propagate selfishness is a self defeating process. If you build it
they will come!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: web browsing short cut

2011-07-02 Thread Chris Rebert
On Sat, Jul 2, 2011 at 6:21 PM, Dustin Cheung  wrote:
> Hey guys,
> I am new to python. I want to make a shortcut that opens my websites
> and re-sizes them to  display on different areas on the screen. I looked
> around but i had no luck. Is that possible with python? if so can someone
> point to to the right direction? Here is what I came up with so far..

The window positioning+resizing bit will likely require using
platform-specific APIs. Since you appear to be on Windows, the
relevant library would be pywin32 (http://pypi.python.org/pypi/pywin32
). You would use it to invoke some COM API that does window
positioning+resizing. I am unable to give more details as I'm on a
Mac.

Sidenote: Have you tried Firefox's "Bookmark All Tabs" feature?

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


Re: Why won't this decorator work?

2011-07-02 Thread Steven D'Aprano
John Salerno wrote:

> But why does the documentation say "The return value of the decorator
> need not be callable"? 

The thing returned by a decorator does not need to be callable, but if you
want to call it, then it better be!

This is no different from this:

my_func = "hello world"
my_func()  # fails because strings aren't callable

So if I do this:

def decorator(func):
# ignores the function and returns a string
return "hello world"

@decorator
def my_func():
x = 1
y = 2
return x+y

print(my_func)  # prints "hello world"
my_func()  # fails because strings aren't callable


If that's useful to you, decorator syntax allows it. That is all the
documentation means.



> And why, if I remove the decorator and just 
> leave the two functions as if, does the call to move(roll_die()) work?
> Isn't that what the decorator syntax is essentially doing?

The call move(roll_die()) is similar to this:

temp = roll_die()
my_string = move(temp)

which is perfectly fine, because you never call my_string. If you did, you'd
get the same error, because strings aren't callable.

The decorator syntax is completely different. It is doing this:

# replace the function roll_die with the output of move, which is a string
roll_die = move(roll_die)  
# now try to call "roll_die", actually a string
roll_die()

which is more like:

move(roll_die)()

See the difference?



-- 
Steven

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


Re: Why won't this decorator work?

2011-07-02 Thread John Salerno
On Jul 2, 9:11 pm, Steven D'Aprano  wrote:
> John Salerno wrote:
> > But why does the documentation say "The return value of the decorator
> > need not be callable"?
>
> The thing returned by a decorator does not need to be callable, but if you
> want to call it, then it better be!
>
> This is no different from this:
>
> my_func = "hello world"
> my_func()  # fails because strings aren't callable
>
> So if I do this:
>
> def decorator(func):
>     # ignores the function and returns a string
>     return "hello world"
>
> @decorator
> def my_func():
>     x = 1
>     y = 2
>     return x+y
>
> print(my_func)  # prints "hello world"
> my_func()  # fails because strings aren't callable
>
> If that's useful to you, decorator syntax allows it. That is all the
> documentation means.
>
> > And why, if I remove the decorator and just
> > leave the two functions as if, does the call to move(roll_die()) work?
> > Isn't that what the decorator syntax is essentially doing?
>
> The call move(roll_die()) is similar to this:
>
> temp = roll_die()
> my_string = move(temp)
>
> which is perfectly fine, because you never call my_string. If you did, you'd
> get the same error, because strings aren't callable.
>
> The decorator syntax is completely different. It is doing this:
>
> # replace the function roll_die with the output of move, which is a string
> roll_die = move(roll_die)  
> # now try to call "roll_die", actually a string
> roll_die()
>
> which is more like:
>
> move(roll_die)()
>
> See the difference?
>
> --
> Steven

Eesh, ok, I think I *still* don't quite get decorators, but I get it a
little more now. Definitely not what I needed to do here. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Anyone want to critique this program?

2011-07-02 Thread John Salerno
Just thought I'd post this in the event anyone has a few spare minutes
and feels like tearing apart a fairly simple attempt to write a
game. :)

I'll paste the exercise I was working on first, although I think it
was meant to be an exercise in how to use lists. I went way beyond
that, so maybe my program is overly complicated. It works, though, so
that's a plus! The main questions I had about it are at the bottom,
after the code.

--
Snakes and Ladders can be a fun game for kids to play but you realize
when you get older that the players actually have no choices at all.
To illustrate just how little input the players have I want you to
make a computer program that allows two players to play snakes and
ladders on the board given.

The rules of the game are simple. On each player's turn they roll one
six sided die and move ahead that many squares.  If they end their
move at the base of a ladder then they automatically climb to the top
of the ladder.  If they end their move at the end of a snake they
automatically slide down to its head. To win the game you must be the
first player to land on the last square.  If you are near the end and
your roll would cause you to go past the end square you don't move for
that turn.

Your computerized version will look something like:
Player 1  hit enter to roll

You rolled: 3
You are at spot 3
Player 2  hit enter to roll

You rolled: 6
You climbed a ladder
You are at spot 17
although you can write this program without using lists, you should
ask yourself how you can use lists to encode where the snakes and
ladders are.
-
(I changed snakes to chutes, and I didn't paste in the game board
picture. Just trust that the dictionary of lists in the beginning of
the program is accurate, and that each set of numbers represents first
the space you land on, and second the space you slide or climb to,
e.g. [30, 35] means you landed on 30, and as a result of landing on a
ladder space, you climbed up to space 35.)

---
import random

game_information = '***Chutes and Ladders***\nUp to four (4) players
may play.\n'\
   'There are 90 spaces on the board. '\
   'The player to reach space 90 first wins.'
separator = '-' * 20
spaces = [None] * 90
c_l_spaces = {r'slid down a chute \\': [[14, 3], [20, 15], [39, 33],
[66, 53],
[69, 58], [79, 67], [84, 71], [88,
36]],
  'climbed up a ladder |=|': [[6, 17], [24, 26], [30, 44],
[49, 62], [82, 86]]}

class Player:

def __init__(self, number):
self.number = number
self.space = 0

def move(self, roll):
global spaces
if (self.space + roll) > 90:
return (1, 'Your roll would move you off the game board.
'\
'You remain at space {0}.'.format(self.space))
elif (self.space + roll) == 90:
return (0, 'You moved to the last space. You won the
game!')
else:
self.space += roll
try:
space_type = spaces[self.space - 1][0]
self.space = spaces[self.space - 1][1]
except TypeError:
return (1, 'You moved to space
{0}.'.format(self.space))
else:
return (1, 'You {0} to space {1}!'.format(space_type,
self.space))

def roll_die():
roll = random.randint(1, 6)
print('You rolled {0}.'.format(roll))
return roll

def populate_game_board():
global spaces
for key, values in c_l_spaces.items():
for space in values:
spaces[space[0] - 1] = [key, space[1]]

def initialize_players():
while True:
try:
num_players = int(input('Enter the number of players (0 to
exit): '))
except ValueError:
print('You have entered an invalid response.\n')
else:
if num_players == 0:
print('You have quit the game.')
return
elif 1 <= num_players <= 4:
break
elif (num_players < 0) or (num_players > 4):
print('You have entered an invalid number of players.
\n')

players = []
for num in range(num_players):
players.append(Player(num + 1))

return players

def start_game(players):
game = 1
while game:
for player in players:
print('\n***Player {0}***'.format(player.number))
print('You are currently on space
{0}.'.format(player.space))
game_update = player.move(roll_die())
print(game_update[1])
print(separator, end='')
if game_update[0] == 0:
game = 0
break
if game:
input('\nPress Enter for the next turn.')

def initialize_game():
global game_information
print(game_information)
players = initialize_players()
if players:
populate_game_board()
start_game(players)

if __name__ == '__main_

Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
On Jul 2, 8:49 pm, Chris Angelico  wrote:
> On Sun, Jul 3, 2011 at 11:43 AM, rantingrick  wrote:
> > I mean what is the point of having two languages with the exact same
> > syntax?
>
> > Ruby: print 'blah'
> > Python: print 'blah'
>
> > Ruby: for x in blah: blah_blah_blah
> > Python: for x in blah: blah_blah_blah
>
> > WHAT?
>
> What's the point of having fifty languages in which "x+y" is an
> expression whose value is the sum of x and y? Let's ditch 'em all and
> just use one language, since _obviously_ the languages have the exact
> same syntax.

It seem ludicrous at first glance but it is true! We have to much re-
inventing going on!

> Common syntax is an aid to learning. It means you can transfer
> knowledge from one language to another. It doesn't make either
> useless.

Why do you constantly propagate multiplicity? Why do you feel that we
need 100 or so languages when about three would cover everything? Sure
people are free to create whatever Frankenstein language they want in
the confines of their hobby time, but we need standards and we need
them NOW.

We want the world and we want it now!
http://www.youtube.com/watch?v=xkp8fNODegU&feature=player_detailpage#t=472s

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


Re: Inexplicable behavior in simple example of a set in a class

2011-07-02 Thread Steven D'Aprano
Saqib Ali wrote:

> I have written two EXTREMELY simple python classes. One class
> (myClass1) contains a data attribute (myNum) that contains an integer.
> The other class (myClass2) contains a data attribute (mySet) that
> contains a set.
> 
> I instantiate 2 instances of myClass1 (a & b). I then change the value
> of a.myNum. It works as expected.
> 
> Then I instantiate 2 instances of myClass2 (c & d). I then change the
> value of c.mySet. Bizarrely changing the value of c.mySet also affects
> the value of d.mySet which I haven't touched at all!?!?! 

But that is wrong -- you HAVE touched it. Look carefully: in myClass2, you
have this:

class myClass2:
mySet = sets.Set(range(1,10))
def clearSet(self):
self.mySet.clear()

mySet is a class attribute, shared by ALL instances, and mySet.clear()
modifies it in place. This is exactly the same as this snippet:


>>> a = set([1, 2, 3])
>>> b = a
>>> b.clear()
>>> a
set([])
>>> b
set([])

In Python, attributes assigned in the class scope are shared between all
instances. Attributes assigned directly on self are not:

class Test:
a = set([1, 2, 3])
def __init__(self):
self.b = set([1, 2, 3])


>>> x = Test()
>>> y = Test()
>>> x.a is y.a  # The same set is shared by both instances.
True
>>> x.b is y.b  # Each instance gets its own set.
False


So why does myClass1 behave differently? Simple: look at the clear method:

class myClass1:
myNum = 9
def clearNum(self):
self.myNum = 0

It assigns a new attribute, rather than modifying the object in place!
Assignment to self.myNum creates a new unshared attribute:

>>> z = myClass1()
>>> z.myNum
9
>>> z.__dict__  # No instance attributes yet.
{}
>>> z.clearNum()
>>> z.__dict__  # Now there is one.
{'myNum': 0}
>>> z.__class__.myNum  # the class attribute still exists
9

The simplest way to fix this is to move the declaration of self.mySet into
the __init__ method.



-- 
Steven

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


Re: Anyone want to critique this program?

2011-07-02 Thread Chris Angelico
On Sun, Jul 3, 2011 at 12:19 PM, John Salerno  wrote:
> Just thought I'd post this in the event anyone has a few spare minutes
> and feels like tearing apart a fairly simple attempt to write a
> game. :)

Sure! You seem to comprehend the basics, which is an order of
magnitude better than some people I've tried to help...

> game_information = '***Chutes and Ladders***\nUp to four (4) players
> may play.\n'\
>                   'There are 90 spaces on the board. '\
>                   'The player to reach space 90 first wins.'

I'd do this with a triple-quoted string - it'll simply go across multiple lines:
game_information = """***Chutes and Ladders***
Up to four (4) players may play.
There are 90 spaces on the board.
The player to reach space 90 first wins."""

> c_l_spaces = {r'slid down a chute \\': [[14, 3], [20, 15], [39, 33],
> [66, 53],
>                                    [69, 58], [79, 67], [84, 71], [88,
> 36]],
>              'climbed up a ladder |=|': [[6, 17], [24, 26], [30, 44],
> [49, 62], [82, 86]]}

It strikes me that this plus populate_game_board() is a little
redundant; you could simply have the target dictionary as a literal:

spaces={14:3, 20:15,  6:17, 24:26}

You can get the description "climbed up a ladder" or "slid down a
chute" by seeing if spaces[space] is more or less than space.

>            try:
>                space_type = spaces[self.space - 1][0]
>                self.space = spaces[self.space - 1][1]
>            except TypeError:
>                return (1, 'You moved to space
> {0}.'.format(self.space))
>            else:
>                return (1, 'You {0} to space {1}!'.format(space_type,
> self.space))

It strikes me as odd to use try/except/else for what's
non-exceptional. I'd either use a regular if block, or possibly
something completely different - like having a list like this:

spaces=list(range(91)) # get a list [0, 1, 2, 3... 90]

And then set the entries that have chutes/ladders, possibly from your
original dict of lists (or something like it):

for space in values:
  spaces[space[0]] = space[1]

Then to see where you end up, just go:
try:
  space=spaces[space]
except ValueError:
  print("That would take you past the end of the board!")

In this instance, except is being used for the exceptional condition,
the case where you blow past the edge of the board - rather than the
more normal situation of simply not hitting a chute/ladder.

>    players = []
>    for num in range(num_players):
>        players.append(Player(num + 1))

Generally, anything that looks like this can become a list
comprehension. It'll be faster (which won't matter here), and briefer.

players = [Player(num+1) for num in range(num_players)]

> def start_game(players):
>
> def initialize_game():
>        start_game(players)
>
> if __name__ == '__main__':
>    initialize_game()

start_game() would be more accurately called play_game(), since it
doesn't return till the game's over. And it's a little odd that
initialize_game() doesn't return till the game's over; I'd be inclined
to have initialize_game() return after initializing, and then have the
main routine subsequently call start_game() / play_game(). Just a
minor naming issue!

> 1. Are the functions I made necessary? Do they do enough or too much?

For the most part, I would say your functions are fine.

> 2. Is there a better way to implement the players than as a class?

Better way? Hard to know. There are many ways things can be done, but
the way you've chosen is as good as any. Certainly it's good enough
for the task you're doing.

> 3. Is there a better way to handle all the print calls that the
> program makes?

Again, I think it's fine. There's a general philosophy of separating
"guts" from "interface" (which would mean isolating all the print
statements from the game logic of moving pieces around), but in
something this small, the only reason to do that is for the sake of
practice. There's not much to be gained in small programs from fifty
levels of indirection.

> 4. Are my try/except blocks used appropriately?

This is the one place where I'd recommend change. Use try/except to
catch exceptional situations, not normalities. If your code is going
through the except block most of the time, there's probably something
wrong. Note I don't say there IS something wrong; it's an example of
code smell, and can be correct.

Your code has much in its favour. I've been wordy in suggestions but
that doesn't mean you have bad code! :)

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


Re: web browsing short cut

2011-07-02 Thread Chris Rebert
> On Sat, Jul 2, 2011 at 7:10 PM, Chris Rebert  wrote:
>> On Sat, Jul 2, 2011 at 6:21 PM, Dustin Cheung  wrote:
>> > Hey guys,
>> > I am new to python. I want to make a shortcut that opens my websites
>> > and re-sizes them to
>> > point to to the right direction? Here is what I came up with so far..
>>
>> The window positioning+resizing bit will likely require using
>> platform-specific APIs. Since you appear to be on Windows, the
>> relevant library would be pywin32 (http://pypi.python.org/pypi/pywin32
>> ). You would use it to invoke some COM API that does window
>> positioning+resizing. I am unable to give more details as I'm on a
>> Mac.
>>
>> Sidenote: Have you tried Firefox's "Bookmark All Tabs" feature?

On Sat, Jul 2, 2011 at 7:34 PM, Dustin Cheung  wrote:
> Hey,
> Thanks for showing me to pywin32. I'll look into it and see what i can come
> up with. Also, I haven't tried the Firefox feature. I thought the bookmark
> all feature only saved one browser with multiple tabs.

Correct. I don't know your precise use-case and thought that this
could possibly be sufficient but significantly less complicated.

> I'm sorry but this
> might be a stupid question but was do you mean by COM API?

COM as in:
http://en.wikipedia.org/wiki/Component_Object_Model

API as in a programming interface:
http://en.wikipedia.org/wiki/Application_programming_interface

It's my understanding that most Windows GUI automation stuff tends to
involve using COM. Again, I don't know specifics, I've just followed
other Windows-specific posts on the mailinglist.

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread Chris Angelico
On Sun, Jul 3, 2011 at 12:24 PM, rantingrick  wrote:
> Why do you constantly propagate multiplicity? Why do you feel that we
> need 100 or so languages when about three would cover everything? Sure
> people are free to create whatever Frankenstein language they want in
> the confines of their hobby time, but we need standards and we need
> them NOW.
>

I specced up "the perfect language" a while ago. It gave you a clean
slate with no facilities but one: Define Operator. Then you define
whatever you want - let's say you start by defining = as assignment.
Give it a precedence and associativity, mark it as binary, and start
using it. Now, define + the same way, and -, and so on. Let's define
the letter 'd' as an operator - a binary or unary operator, such that
'2d6' means 'roll two six-sided dice, return the sum' (and unary 'd20'
is equivalent to binary '1d20').

What's wrong with this language? It doesn't do anything, and it does
everything. You could use the language for one thing and I use it for
another thing. There is NO connection. We may as well be using
different languages.

You could have three languages in the world, if one is assembly
language (for the one chip that everyone uses), one is this
clean-slate language, and one is C. Have we improved anything? No. It
won't be any easier to write an API for something; and it'll be a lot
harder to maintain code ("wait wha? This programmer's defined + and *
in opposite precedence to usual!"). But hey, there's only one language
that you need to learn!

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread Steven D'Aprano
rantingrick wrote:

> Hello fellow programmers, scripters, hackers, and debutantes.


Your ideas are intriguing to me and I wish to subscribe to your newsletter.



-- 
Steven

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


Re: Anyone want to critique this program?

2011-07-02 Thread John Salerno
On Jul 2, 10:02 pm, Chris Angelico  wrote:

> > game_information = '***Chutes and Ladders***\nUp to four (4) players
> > may play.\n'\
> >                   'There are 90 spaces on the board. '\
> >                   'The player to reach space 90 first wins.'
>
> I'd do this with a triple-quoted string - it'll simply go across multiple 
> lines:
> game_information = """***Chutes and Ladders***
> Up to four (4) players may play.
> There are 90 spaces on the board.
> The player to reach space 90 first wins."""

Yeah, I considered that, but I just hate the way it looks when the
line wraps around to the left margin. I wanted to line it all up under
the opening quotation mark. The wrapping may not be as much of an
issue when assigning a variable like this, but I especially don't like
triple-quoted strings that wrap around inside function definitions.
That seems to completely throw off the indentation. Do people still
use triple-quotes in that situation?

> > c_l_spaces = {r'slid down a chute \\': [[14, 3], [20, 15], [39, 33],
> > [66, 53],
> >                                    [69, 58], [79, 67], [84, 71], [88,
> > 36]],
> >              'climbed up a ladder |=|': [[6, 17], [24, 26], [30, 44],
> > [49, 62], [82, 86]]}
>
> It strikes me that this plus populate_game_board() is a little
> redundant; you could simply have the target dictionary as a literal:
>
> spaces={14:3, 20:15,  6:17, 24:26}
>
> You can get the description "climbed up a ladder" or "slid down a
> chute" by seeing if spaces[space] is more or less than space.

Hmm, interesting. I'm not quite sure how I'd implement that yet, but
the "14:3" structure seems cleaner (although I admit at first it
looked weird, because I'm used to seeing strings as dictionary
keywords!).

> >            try:
> >                space_type = spaces[self.space - 1][0]
> >                self.space = spaces[self.space - 1][1]
> >            except TypeError:
> >                return (1, 'You moved to space
> > {0}.'.format(self.space))
> >            else:
> >                return (1, 'You {0} to space {1}!'.format(space_type,
> > self.space))
>
> It strikes me as odd to use try/except/else for what's
> non-exceptional. I'd either use a regular if block, or possibly
> something completely different - like having a list like this:
>
> spaces=list(range(91)) # get a list [0, 1, 2, 3... 90]
>
> And then set the entries that have chutes/ladders, possibly from your
> original dict of lists (or something like it):
>
> for space in values:
>   spaces[space[0]] = space[1]
>
> Then to see where you end up, just go:
> try:
>   space=spaces[space]
> except ValueError:
>   print("That would take you past the end of the board!")
>
> In this instance, except is being used for the exceptional condition,
> the case where you blow past the edge of the board - rather than the
> more normal situation of simply not hitting a chute/ladder.

Originally I didn't have the try/except at all, I had nested if
statements that seemed to be getting out of control. Then I realized
if I just attempted to index the list and handle the exception, rather
than check first if indexing the list was allowed, the code came out
cleaner looking. But I agree with you, my "exception" is actually the
more frequent occurrence, so I'm going to change that.

> >    players = []
> >    for num in range(num_players):
> >        players.append(Player(num + 1))
>
> Generally, anything that looks like this can become a list
> comprehension. It'll be faster (which won't matter here), and briefer.
>
> players = [Player(num+1) for num in range(num_players)]

Now this is the kind of tip I love. Something like list comprehensions
just didn't even occur to me, so I'm definitely going to change that.

> > def start_game(players):
>
> > def initialize_game():
> >        start_game(players)
>
> > if __name__ == '__main__':
> >    initialize_game()
>
> start_game() would be more accurately called play_game(), since it
> doesn't return till the game's over. And it's a little odd that
> initialize_game() doesn't return till the game's over; I'd be inclined
> to have initialize_game() return after initializing, and then have the
> main routine subsequently call start_game() / play_game(). Just a
> minor naming issue!

Minor or not, it makes sense. I'm picky about things like that too, so
now that you've pointed it out, I'm compelled to change the names so
they make sense! :)

> > 2. Is there a better way to implement the players than as a class?
>
> Better way? Hard to know. There are many ways things can be done, but
> the way you've chosen is as good as any. Certainly it's good enough
> for the task you're doing.

Yeah, I don't need to know 10 different ways to do things. Mainly I
asked this question because the original exercise seemed to focus on
using lists to write the game, and I just couldn't think of an
efficient way to use a list to store the player attributes like what
space they were on. It just seemed a natural can

Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread Gregory Ewing

The place where this "Unity API" idea of yours falls down
is that an API is only truly easy to use when it's designed
to closely match the characteristics of the language it's
being used from.

For example, Python has a very powerful feature that most
other languages don't have anything remotely like: very
flexible keyword arguments.

A truly Pythonic API will take advantage of them wherever
it makes sense. An extreme example is PyGUI, where you can
write things like

  win = Window(title = "Fred", width = 300, height = 100,
position = (30, 50), movable = True, resizable = True)

In fact, almost *any* attribute of any PyGUI object can be
specified using keyword arguments in the constructor. In
your typical C or C++ based API, either you have a constructor
taking a zillion positional parameters that all have to be
in the right order, or you have to set all the attributes
individually afterwards:

  win = Window()
  win.title = "Fred"
  win.width = 300
  win.height = 100
  win.position = (30, 50)
  win.movable = True
  win.resizable = True

Either way you end up with an API that feels very awkward
when used from Python.

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


Re: Anyone want to critique this program?

2011-07-02 Thread Chris Angelico
On Sun, Jul 3, 2011 at 1:41 PM, John Salerno  wrote:
> Yeah, I considered that, but I just hate the way it looks when the
> line wraps around to the left margin. I wanted to line it all up under
> the opening quotation mark. The wrapping may not be as much of an
> issue when assigning a variable like this, but I especially don't like
> triple-quoted strings that wrap around inside function definitions.
> That seems to completely throw off the indentation. Do people still
> use triple-quotes in that situation?

Jury's out on that one. You can either back-tab it to the left (looks
ugly), or indent it and then clean it up in code (IS ugly). Up to you
to figure out what's best for your code, and if you want to indent it,
your current way is quite possibly the cleanest.

> Minor or not, it makes sense. I'm picky about things like that too, so
> now that you've pointed it out, I'm compelled to change the names so
> they make sense! :)

:) Names tend to stay the same when the functions they're attached to
grow and shift. Sometimes you end up with these great warts in huge
production code... it's sometimes just too much work to change things.

> Thanks a lot for the tips! I'm going to go back over the whole thing
> and rework some of it. And I'm only doing this for the sake of
> learning, so even the small tips help me to think more like a
> programmer. :)

Learning's good! And Python's an excellent language for the purpose.
Code quickly, invoke quickly (no compilation stage), and see the
results of the work.

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread Gregory Ewing

rantingrick wrote:


Ruby: for x in blah: blah_blah_blah
Python: for x in blah: blah_blah_blah


Here you're making the mistake of thinking that surface syntax
is all that matters. Although the 'for' statements in Python and
Ruby look very similar, underneath they're based on quite
different mechanisms. They're not equivalent: the Python way
leads to various powerful things such as generators; the Ruby
way lends itself more to user-defined control structures.

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread Gregory Ewing

Chris Angelico wrote:


Your proposed "Unity API" (which I assume has nothing to do with Natty
Narwhal's preferred interface) already exists. It's the C language.


Or maybe GObject Introspection is closer to what you
have in mind?

A library that supports GI advertises enough information
about itself for dynamic languages such as Python and Ruby
to automatically construct fairly object-oriented interfaces.

It's not perfect, though; for example, the old PyGtk module
used to let you access most of what Gtk calls "properties"
using Python attribute access, but with GI you have to
call the get_property and set_property functions. Also
you often can't just call a class to construct an object,
but have to call a separate constructor function instead.

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
On Jul 2, 10:14 pm, Chris Angelico  wrote:
> I specced up "the perfect language" a while ago. It gave you a clean
> slate with no facilities but one: Define Operator. [...]

That was some great satire :) but the last thing we need is users with
that much power. Take the example of Ruby allowing you to redefine
built in types... disastrous. I understand that freedom is good
however unbridled freedom is a recipe for disaster.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why won't this decorator work?

2011-07-02 Thread Gregory Ewing

Ian Kelly wrote:

If it's not a callable, then the result
will just be that something non-callable is bound to the "roll_die"
name -- which could be useful, but is probably a bad idea in general.


There are legitimate uses -- for example, the following
is a convenient way of creating a read-only property:

  @property
  def foo(self):
return self.calculate_value_of_foo()

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
On Jul 2, 10:57 pm, Gregory Ewing  wrote:
> The place where this "Unity API" idea of yours falls down
> is that an API is only truly easy to use when it's designed
> to closely match the characteristics of the language it's
> being used from.
>
> For example, Python has a very powerful feature that most
> other languages don't have anything remotely like: very
> flexible keyword arguments.

[...]

>
>    win = Window(title = "Fred", width = 300, height = 100,
>      position = (30, 50), movable = True, resizable = True)

With all due respect that's a frail argument Greg. I agree that
python's keyword arguments are great but they can actually cause code
to get messy when so many are passed in a notation like you present
*ahem* ESPECIALLY when "somebody" refuses to follow the style guide
(hint-hint).

I would do this for clarity...

win = Window(
title="Fred",
width=300,
height=100,
position=(30, 50),
movable=True,
resizable=True,
)

psst: removed python style guide abominations :-)
Strangely however it looks very similar to your next notation...

>    win = Window()
>    win.title = "Fred"
>    win.width = 300
>    win.height = 100
>    win.position = (30, 50)
>    win.movable = True
>    win.resizable = True

hmm? I think it's actually easier to read in this final form. However
i will agree that C's requirements for function parameters are a real
pain in the arse. Thank Guido for Python!

> Either way you end up with an API that feels very awkward
> when used from Python.

I think we need to provide a better example (than just mere
conjecture) before we assume how an "imaginary" API would "feel". And
don't forget, any API can feel awkward since you've only got the hooks
that the devs deemed worthy for you to have. I can't tell you how many
obstacles I've had to code around because an API was lacking or buggy.
Turned my otherwise beautiful code into an Orwellian nightmare.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread rantingrick
On Jul 2, 11:00 pm, Gregory Ewing  wrote:
> rantingrick wrote:
> > Ruby: for x in blah: blah_blah_blah
> > Python: for x in blah: blah_blah_blah
>
> Here you're making the mistake of thinking that surface syntax
> is all that matters. Although the 'for' statements in Python and
> Ruby look very similar, underneath they're based on quite
> different mechanisms. They're not equivalent: the Python way
> leads to various powerful things such as generators; the Ruby
> way lends itself more to user-defined control structures.

I agree however i see merit in both approaches. But why must we have
completely different languages just for that those two approaches? We
don't it's just a religious thing.  Doesn't make sense to me. If Guido
and Matz got together over some sake and Monty Python i'll bet they
could hash out a singular replacement fro Ruby and Python in no time!

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


Re: The end to all language wars and the great unity API to come!

2011-07-02 Thread Steven D'Aprano
rantingrick wrote:

> Turned my otherwise beautiful code into an Orwellian nightmare.

Your code was spying on you, having your friends and family disappear during
the night to be tortured, and having history re-written so that there was
no longer any evidence that they ever existed?

You have my sympathy.


-- 
Steven

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


Re: from module import * using __import__?

2011-07-02 Thread Terry Reedy

On 7/2/2011 12:52 PM, Dan Stromberg wrote:


Is there a decent way of running "from  import *"?  Perhaps
using __import__?

Does it mean using the copy module or adding an element to globals()
somehow?

Yes, I think I do have a good use for this: importing either pure python
or cython versions of a module into a single namespace that can provide
the same interface (transparent to the caller), whether C extension
modules are viable in the current interpreter or not.  So you have a
stub module that provides one or the other, depending on availability
and suitability.


I suggest you look at some of the Python module that import native code 
implementations when available. heapq for one. maybe functools.


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