Re: I am a newbie for python and try to understand class Inheritance.

2011-10-15 Thread Chris Rebert
On Fri, Oct 14, 2011 at 11:20 PM,   wrote:
> Test.py
> #!/usr/bin/python
> from my_lib import my_function
> class my_class(my_function.name):

Why are you subclassing my_function.name and not just my_function?

>    def __initial__(self, name);
>         pass

The initializer method should be named "__init__", not "__initial__".

>    def test():

You forgot to include "self" as a parameter, like so:
def test(self):

>       print "this is a test"
>
> If __name__ == '__maim__':

That should be "__main__" with an N, not "__maim__" with an M.
And "if" must be in all-lowercase.

>    my_class.main()

Your class doesn't define any method named "main" (you only defined
test() and __initial__() ), so this call will fail.

> ---
> my_lib.py
> class my_function()

You're missing a colon after the parentheses. Also, you're writing a
class, not a function, so please rename the class something less
confusing.

> Can anyone finish above code and let me try to understand
> Class inheritance?
> TIA.

Have you read any Python tutorial? There are several basic errors in
your code which would suggest that you haven't. You really ought to;
it's well worth it.
The Beginner's Guide links to 2 lists of tutorials:
http://wiki.python.org/moin/BeginnersGuide

There's also the python-tutor mailing list, which is specifically
geared towards answering beginner questions:
http://mail.python.org/mailman/listinfo/tutor

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


Re: I am a newbie for python and try to understand class Inheritance.

2011-10-15 Thread Jason Swails
On Sat, Oct 15, 2011 at 2:20 AM,  wrote:

> Test.py
> #!/usr/bin/python
> from my_lib import my_function
> class my_class(my_function.name):
>

Classes must inherit from other classes -- not variables or functions.


>def __initial__(self, name);
>

This should be "def __init__(self, name):" (: not ; and __init__, not
__initial__)

pass
>def test():
>   print "this is a test"
>
> If __name__ == '__maim__':
>

I think this should be '__main__'


>my_class.main()
>

This only makes sense if your my_class has a main() attribute function to
it.  Note that the typical way of dealing with classes is to instantiate
different classes.


>
> Can anyone finish above code and let me try to understand
> Class inheritance?
>

You appear to be confusing functions and classes.  Functions are chunks of
code that you (optionally) pass variables to in order to perform a specific
task.  Classes, on the other hand, are the heart of OOP.  They are useful
for creating an abstraction layer to make certain problems easier and
reading code easier as well.  (It also helps break down the problem into
more manageable pieces, which facilitates collaborative projects).

For instance, let's say you want to deal with shapes.  You can define a
shape via a class

class Shape(object):
   """ Base shape class """
   def __init__(self, vertices):
  """ Obviously if any of the vertices are collinear num_sides will be
wrong. This is an example """
  self.vertices = vertices
  self.num_sides = len(vertices)
   def draw(self, canvas):
  """ Draws the given shape on a passed canvas. Pretend there is working
code here """
   def area(self):
  """ Calculates the area of this shape and returns it as a floating
point number """
  return 

Now you can create different shapes as you need them

user_shape_1 = Shape( ((0,0), (0,1), (1,1), (1,0)) )
user_shape_2 = Shape( ((-1,-1), (0,0), (-1,0)) )

Now you have 2 different shapes.  If you have some kind of canvas object
(from Tk, perhaps), you can draw either shape up there by calling one of its
functions:

user_shape_1.draw(my_canvas)

As you can see, the simple call user_shape_1.draw(my_canvas) is self
explanatory -- it draws the shape on the given canvas.  This allows easy
re-use of code.

Now we get into inheritance.  Let's suppose that we want a specific type of
shape.  For instance, a circle (that is defined by an infinite number of
vertices).  In this case, a circle is still a shape, so it should have every
attribute that a normal shape has.  Thus, we can define a circle class as
follows:

class Circle(Shape):
   """ Circle inherits from Shape """
   number_vertex_points = 1000 # Default number of vertex points I want to
define a circle
   def __init__(self, center, radius):
  """ Define the self.vertices here to trace out a circle as closely as
you want """

Now, each time we instantiate a Circle class, that class has every attribute
that Shape has, in addition to any additional attribute you give to Circle
(and if the same attribute is defined in both places, the definition in
Circle overrides that definition).  Thus, in this case we can define a
Circle with a center and radius (much easier than vertices!), and we can
tell Circle how we want the vertices defined to get as close an
approximation to a circle as we want.

HTH (I'm sure others can explain this better than I can),
Jason
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I am a newbie for python and try to understand class Inheritance.

2011-10-15 Thread Chris Rebert
On Sat, Oct 15, 2011 at 12:09 AM, Jason Swails  wrote:

> For instance, let's say you want to deal with shapes.  You can define a
> shape via a class
>
> class Shape(object):
>    """ Base shape class """

> Now we get into inheritance.  Let's suppose that we want a specific type of
> shape.  For instance, a circle (that is defined by an infinite number of
> vertices).  In this case, a circle is still a shape, so it should have every
> attribute that a normal shape has.  Thus, we can define a circle class as
> follows:
>
> class Circle(Shape):
>    """ Circle inherits from Shape """
>    number_vertex_points = 1000 # Default number of vertex points I want to
> define a circle
>    def __init__(self, center, radius):
>   """ Define the self.vertices here to trace out a circle as closely as
> you want """
>
> Now, each time we instantiate a Circle class, that class has every attribute
> that Shape has, in addition to any additional attribute you give to Circle
> (and if the same attribute is defined in both places, the definition in
> Circle overrides that definition).  Thus, in this case we can define a
> Circle with a center and radius (much easier than vertices!), and we can
> tell Circle how we want the vertices defined to get as close an
> approximation to a circle as we want.

Sidenote: It's funny that the shapes example gets used so often,
despite the fact that pursuing it much further so easily leads to the
Circle-Ellipse / Rectangle-Square problem.

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


Re: I am a newbie for python and try to understand class Inheritance.

2011-10-15 Thread aaabbb16
On 10月15日, 上午12时04分, Chris Rebert  wrote:
> On Fri, Oct 14, 2011 at 11:20 PM,   wrote:
> > Test.py
> > #!/usr/bin/python
> > from my_lib import test
> > class my_class(my_function.name):
>
> Why are you subclassing my_function.name and not just my_function?
try to inherit or change "name" attribute in "my_function".
>
> >    def __initial__(self, name);
> >         pass
>
> The initializer method should be named "__init__", not "__initial__".
ipad is so smart, it thinks I have spelling problem and
correct it. haha. sorry about it.
>
> >    def test():
>
> You forgot to include "self" as a parameter, like so:
>     def test(self):
right thanks!
>
> >       print "this is a test"
>
> > If __name__ == '__maim__':
>
> That should be "__main__" with an N, not "__maim__" with an M.
> And "if" must be in all-lowercase.
mistyping

> >    my_class.main()
>
> Your class doesn't define any method named "main" (you only defined
> test() and __initial__() ), so this call will fail.
how to do it?
> > ---
> > my_lib.py
> > class my_function()
>
> You're missing a colon after the parentheses. Also, you're writing a
> class, not a function, so please rename the class something less
> confusing.
sure. i like call it from my_lib
>
> > Can anyone finish above code and let me try to understand
> > Class inheritance?
> > TIA.
>
> Have you read any Python tutorial? There are several basic errors in
> your code which would suggest that you haven't. You really ought to;
> it's well worth it.
> The Beginner's Guide links to 2 lists of 
> tutorials:http://wiki.python.org/moin/BeginnersGuide
>
> There's also the python-tutor mailing list, which is specifically
> geared towards answering beginner 
> questions:http://mail.python.org/mailman/listinfo/tutor
>
> Cheers,
> Chris
> --http://rebertia.com

Thanks Chris! I'll check that link.

Test.py
#!/usr/bin/python
from my_lib import p_test
class my_class(p_test.name):
def __initial__(self, name):
 pass
def test(self):
   print "this is a test"

If __name__ == '__main__':
my_class.main()
---
my_lib.py
class p_test()
...


Can anyone finish it and give me a demo.
Class inheritance?
for this case, it inherit/change p_test "name" attribute.
I try to quick understand how to inherit parent attribute
TIA.
david
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I am a newbie for python and try to understand class Inheritance.

2011-10-15 Thread Chris Rebert
On Sat, Oct 15, 2011 at 12:59 AM,   wrote:
> On 10月15日, 上午12时04分, Chris Rebert  wrote:
>> On Fri, Oct 14, 2011 at 11:20 PM,   wrote:

>> >    my_class.main()
>>
>> Your class doesn't define any method named "main" (you only defined
>> test() and __initial__() ), so this call will fail.
> how to do it?

You'd define a method named "main", just like with "test".
You would then call it by doing:
my_class().main()


> Test.py
> #!/usr/bin/python
> from my_lib import p_test
> class my_class(p_test.name):
>    def __initial__(self, name):
>         pass
>    def test(self):
>       print "this is a test"
>
> If __name__ == '__main__':
>    my_class.main()
> ---
> my_lib.py
> class p_test()
> ...
> 
>
> Can anyone finish it and give me a demo.
> Class inheritance?
> for this case, it inherit/change p_test "name" attribute.
> I try to quick understand how to inherit parent attribute

my_lib.py:
class ParentClass(object):
def __init__(self, name):
self.name = name
self.species = "Human"

test.py:
from my_lib import ParentClass

class MyClass(ParentClass):
def __init__(self, name):
super(MyClass, self).__init__(name + " Jones")
def print_name(self):
print "My name is", self.name
print "And I am a", self.species

MyClass("Bob").print_name()


Note that classes are conventionally named using CamelCaseLikeThis
instead of underscore_separated_words.

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


Re: why msvcrt.printf show the first char only?

2011-10-15 Thread Gabriel Genellina
On 12 oct, 08:50, Nobody  wrote:
> On Wed, 12 Oct 2011 04:18:25 -0700, install...@189.cn wrote:
> > from ctypes import *
> > msvcrt = cdll.msvcrt
> > message_string = "Hello world!\n"
> > print(msvcrt.printf("Testing: %s", message_string))
>
> > when running in eclipse, the result is:
> > 1
> > T
>
> > when running in IDLE, then result is:
> > 1
>
> > why is that?
>
> Odd. I get 22 when running from IDLE.
>
> Also, when using the console, it actually prints the text. I suspect that
> stdout gets block-buffered when using an IDE. I can't see any way to get a
> reference to stdout, so you can't fflush() it.

Launch IDLE from the command line and you'll see the text output.

To the OP: I bet your Eclipse runs Python 2.x and IDLE is 3.x.

In Python 3.x, "Test..." is a Unicode string, internally represented
using two bytes per character. (In contrast, in Python 2.x, "Test..."
is a byte string, and u"Test..." is unicode). All ASCII characters
have a 0 as their second byte in its internal representation. printf
expects a byte string, and stops as soon as it sees the '\0' following
the 'T' in 'Testing'. Either use wprintf("Testing..."), or encode the
Unicode object into a byte string before calling:
printf("Testing...".encode(sys.stdout.encoding)), or tell ctypes about
the right parameter type:

printf = msvcrt.printf
printf.argtypes = [c_char_p]
printf("Testing\n")

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


Re: Site to open blocked sites, and prohibited and encoded

2011-10-15 Thread Alec Taylor
Large list: http://proxy.org/

On Sat, Oct 15, 2011 at 7:44 PM, porxy  wrote:
> Site to open blocked sites, and prohibited and encoded
>
> http://myway.x90x.net/
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Want to make the transition to games?

2011-10-15 Thread Chris Withers
Please don't spam this list with jobs, especially if they have nothing 
to do with Python.


If they do, use the job board instead:

http://www.python.org/community/jobs/howto/

cheers,

Chris

On 12/10/2011 05:49, Marta wrote:

Hi,

I'm working as an onsite recruiting consultant and we are looking for
top engineers who want to work with other very accomplished
engineers.  If you have a CS degree, strong in C++ and want to make
the transition to games, please email me your resume.

Cheers,

Marta Daglow


--
Simplistix - Content Management, Batch Processing & Python Consulting
- http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: Seven Python Developers Needed $125K

2011-10-15 Thread Chris Withers

I'd suggest you post to the job board rather than spamming the list:

http://www.python.org/community/jobs/howto/

cheers,

Chris

On 11/10/2011 19:16, WR wrote:

Top Global Consulting Firm in NYC needs 7 Python Developers

Up to $125K depending on experience

Solid knowledge of fundamental Python concepts.  At least three years Python 
experience required.

For more info email jos...@washresearch.com

Joseph Ryan
Washington Research Associates Inc
(202) 408-7025



--
Simplistix - Content Management, Batch Processing & Python Consulting
- http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: argparse zero-length switch

2011-10-15 Thread Steven D'Aprano
Carl Banks wrote:

> So instead of typing this:
> 
> sp subcommand -s abc foo bar
> 
> they could type this:
> 
> sp subcommand @abc foo bar
> 
> Admittedly a small benefit.


I would call it a *cost* and not a benefit at all. Instead of using a
standard, familiar user interface for entering command options, you
introduce a second special purpose mechanism *just* for entering a section
name. -s is at least a mnemonic for "section", @ is not.

And it isn't like you gain any extra clarity or expressiveness, or even a
major saving of typing! "-s" vs "@". You don't even save a key stroke: "@"
requires two keystrokes, just as "-s" does. (Okay, perhaps you save a key
stroke if you type a space after the -s.)

-s section_name is pretty simple already. Spelling it @section_name is not
sufficiently more simple to make up for the burden of introducing
unfamiliar syntax.



-- 
Steven

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


Re: Can I search a list for a range of values?

2011-10-15 Thread Steven D'Aprano
Chris Angelico wrote:


> Yeah, it's legal because you can nest fors and ifs in a list comp.
> Stylistic difference, I used "if" instead of "and" because there's no
> way that it could be a bitwise and.

If you're using Python, there's no way that it could be a bitwise and.


> (It's a cross-language safety net that I sometimes use.) 

I'm not familiar with a language that uses Python syntax but "and" is a
bitwise and. Which language is that?


-- 
Steven

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


Re: Opportunity missed by Python ?

2011-10-15 Thread 88888 dihedral
Conversion utilities are used to ease the  burdens for programmers to  
translate  source scripts  and codes into different languages or even the same 
language with revisions. Check for translators for C, C++, PASCAL, BASIC, and 
FORTRAN and also  SWIG, PYREX, CYTHON, JYTHON  and etc.. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I search a list for a range of values?

2011-10-15 Thread Chris Angelico
On Sat, Oct 15, 2011 at 10:53 PM, Steven D'Aprano
 wrote:
> I'm not familiar with a language that uses Python syntax but "and" is a
> bitwise and. Which language is that?
>

I'm not familiar with any either, it's just that I have a few habits
that I slip into.

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


Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-15 Thread Grant Edwards
On 2011-10-14, Westley Mart?nez  wrote:
> On Thu, Oct 13, 2011 at 11:56:20PM -0700, Carl Banks wrote:
>
> While we're at it, let's throw in the register keyword.

Yah!  C compilers have been ignoring it for ages, and I miss it.

-- 
Grant

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


Re: Fwd: os.statvfs bug or my incompetence ?

2011-10-15 Thread Kev Dwyer
Peter G. Marczis wrote:



Hello Peter,

Welcome to the list.

Have you tried calling statvfs from a C program?  What happens if you do?

Best regards,

Kev




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


Help with beginner form using lpthw.web

2011-10-15 Thread pngrv
Hey -- 

I'm still learning what all of the different exceptions and errors mean. What 
I'd like to do is grab a bit of assistance figuring out the error I'm getting 
so that I can keep moving.

My python code for this particular part of the app looks like this:

class rs_request:
def GET(self):
return render.rs_request()

def POST(self):
form = web.input(name='Dood', project='Awesome', locations='1', 
engines='1')
request_string = 'Request: %s, %s, %s, %s' % (form.name, form.project, 
form.locations, form.engines)
return render.index(request_string = request_string) 


My HTML:


 
  Please Use This Form To Request Resources
 
 
 
Name: 
Project: 
# of Locations: 
# of Engines: 

 1
 2
 3
 4
 5
 6
 7
 8
 9+


  
$def with (request_string)
$if request_string:
I just wanted to say $request_string.
$else:
Hello, world!
 


And seeing this error:
 at /rs_request
invalid syntax Template traceback: File 'templates/rs_request.html', line 30 
 (rs_request.html, line 30)

Python  /Library/Python/2.7/site-packages/web/template.py in compile_template, 
line 909
Web GET http://localhost:8080/rs_request

So, it seems to be indicating that my GET request is broken, but I don't really 
understand why. Can anyone help?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Opportunity missed by Python ?

2011-10-15 Thread geremy condra
On Fri, Oct 14, 2011 at 5:49 PM, alex23  wrote:
> On Oct 13, 8:07 pm, Chris Angelico  wrote:
>> Python, as I found out to my detriment, is practically impossible to
>> sandbox effectively.
>
> The latest version of PyPy introduces a prototype sandbox:
>
> http://pypy.org/features.html#sandboxing
>
> It'll be interesting to see how effective this is.

Please note that their sandbox, while a good idea, is not a guaranteed
jail. It's enforced by replacing calls to external libraries with
trampoline stubs, but does not appear to have any intrinsic mechanism
to prevent calls from being issued without it. That means that if you
were able to successfully inject code you would be no more protected
here than with any other process.

Geremy Condra

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


Re: Opportunity missed by Python ?

2011-10-15 Thread 88888 dihedral
The undetected recursive call loop in some states that can be hacked or would 
hang and crush! Every program has to be run in a VM is just one solution but 
that will slow down a lot. 
-- 
http://mail.python.org/mailman/listinfo/python-list


hi can someone help please key bind

2011-10-15 Thread Gary

Hi im trying to use key bind on Tkinter to call this function

def Start():
for i in range(60,-1,-1):
ent['text'] = i
  time.sleep(1)
  root.update()
ent['text'] = 'Time Out!'
root.update()

i know the function is ok as i have assigned a button and i calls the 
function as i expect

but
root.bind('',Start)
gives the following error

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__
return self.func(*args)
TypeError: Start() takes no arguments (1 given)

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


Python hangs: Problem with wxPython, threading, pySerial, or events?

2011-10-15 Thread Ethan Swint

Hi-

I'm experiencing crashes in my Win32 Python 2.7 application which appear 
to be linked to pyzmq.  At the moment, I can't even kill the "python.exe 
*32" process in the Windows Task Manager.  At the moment I'm running the 
script using Ipython by calling


C:\Python27\pythonw.exe "/python27/scripts/ipython-qtconsole-script.pyw" 
-pylab


but I also experience similar behavior when running within Eclipse.  
I've included an error message at the end which appears in the Windows 
'cmd' window, but the message is not reflected in the pylab window.


My attached device is transmitting <160><1><2><3><4><80> and is received 
correctly when I run the sample pyserial script 'wxTerminal.py'.  In my 
application, however, the message appears to get characters out of order 
or drop bytes.


If there's a better place to post or if you'd like more info, let me know.

Thanks,
Ethan

--Serial Port Listening 
Thread

def MotorRxThread(self):
"""Thread that handles the incoming traffic. Does buffer input and 
generates an SerialRxEvent"""

while self.alive.isSet():   #loop while alive event is true
  text = self.serMotor.read(1)  #read one, with timeout
  if text:#check if not timeout
n = self.serMotor.inWaiting() #look if there is more to read
if n:
  text = text + self.serMotor.read(n) #get it
#log to terminal
printstring = "MotorRxThread: "
for b in text:
  printstring += str(ord(b)) + " "
print printstring
#pdb.set_trace()
if self.motorRx0.proc_string(text):
  print "Message: cmd: " + str(self.motorRx0.cmd) + " data: " + 
str(self.motorRx0.data)

  event = SerialRxSpeedEvent(self.GetId(), text)
  self.GetEventHandler().AddPendingEvent(event)
-\Serial Port Listening 
Thread


Thread 
Start&Stop--

  def StartMotorThread(self):
"""Start the receiver thread"""
self.motorThread = threading.Thread(target=self.MotorRxThread)
self.motorThread.setDaemon(1)
self.alive.set()
self.motorThread.start()

  def StopMotorThread(self):
"""Stop the receiver thread, wait until it's finished."""
if self.motorThread is not None:
self.alive.clear()  #clear alive event for thread
self.motorThread.join()  #wait until thread has finished
self.motorThread = None
self.serMotor.close()  #close the serial port connection
\Thread 
Start&Stop--


---Error message 


ValueError: '' is not in list
([], ['', '', '', 
'{"date":"2011-10-15T10:24:27.231000","username":"kernel","session":"82906c8a-1235-44d0-b65d-
0882955305c1","msg_id":"7cfcd155-bc05-4f47-9c39-094252223dab","msg_type":"stream"}', 
'{"date":"2011-10-15T10:24:27.23100

0","username":"kernel","session":"82906c8a-1235-44d0-b65d-0882955305c1","msg_id":"f4b88228-b353-4cfb-9bbe-ae524ee1ac38",
"msg_type":"stream"}', 
'{"date":"2011-10-15T10:24:00.774000","username":"username","session":"9f393860-c2ab-44e9-820d-8f
08ae35044e","msg_id":"13a46e93-8da2-487b-ab12-6cae47b1ac34","msg_type":"execute_request"}', 
'{"date":"2011-10-15T10:24:0

0.774000","username":"username","session":"9f393860-c2ab-44e9-820d-8f08ae35044e","msg_id":"13a46e93-8da2-487b-ab12-6cae4
7b1ac34","msg_type":"execute_request"}', '{"data":"\\nMotorRxThread: 0 
MotorRxThread: 4 ","name":"stdout"}'])
ERROR:root:Exception in I/O handler for fd object at 0x03ADFCC0>

Traceback (most recent call last):
  File 
"C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\ioloop.py", 
line 291, in start

self._handlers[fd](fd, events)
  File 
"C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\stack_context.py", 
line 133, in wrapped

callback(*args, **kwargs)
  File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", 
line 448, in _handle_events

self._handle_recv()
  File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", 
line 458, in _handle_recv

ident,msg = self.session.recv(self.socket)
  File "C:\Python27\lib\site-packages\IPython\zmq\session.py", line 
585, in recv

raise e
ValueError: No JSON object could be decoded
ERROR:root:Exception in I/O handler for fd object at 0x03ADFCC0>

Traceback (most recent call last):
  File 
"C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\ioloop.py", 
line 291, in start

self._handlers[fd](fd, events)
  File 
"C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\stack_context.py", 
line 133, in wrapped

callback(*args, **kwargs)
  File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", 
line 448, in _hand

Loop through a dict changing keys

2011-10-15 Thread Gnarlodious
What is the best way (Python 3) to loop through dict keys, examine the
string, change them if needed, and save the changes to the same dict?

So for input like this:
{'Mobile': 'string', 'context': '', 'order': '7',
'time': 'True'}

I want to booleanize 'True', turn '7' into an integer, escape
'', and ignore 'string'.

Any elegant Python way to do this?

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


Re: hi can someone help please key bind

2011-10-15 Thread MRAB

On 15/10/2011 18:30, Gary wrote:

Hi im trying to use key bind on Tkinter to call this function

def Start():
for i in range(60,-1,-1):
ent['text'] = i
  time.sleep(1)
  root.update()
ent['text'] = 'Time Out!'
root.update()

i know the function is ok as i have assigned a button and i calls the 
function as i expect

but
root.bind('',Start)
gives the following error

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__
return self.func(*args)
TypeError: Start() takes no arguments (1 given)

The function will be called with an 'event' parameter, but you've 
defined it function to accept no

parameters, hence the error message.

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


Re: Loop through a dict changing keys

2011-10-15 Thread MRAB

On 15/10/2011 19:00, Gnarlodious wrote:

What is the best way (Python 3) to loop through dict keys, examine the
string, change them if needed, and save the changes to the same dict?

So for input like this:
{'Mobile': 'string', 'context': '', 'order': '7',
'time': 'True'}

I want to booleanize 'True', turn '7' into an integer, escape
'', and ignore 'string'.

Any elegant Python way to do this?


How about:

for key, value in my_dict.items():
if value == "True":
my_dict[key] = True
--
http://mail.python.org/mailman/listinfo/python-list


Re: hi can someone help please key bind

2011-10-15 Thread Alexander Kapps

On 15.10.2011 19:30, Gary wrote:

Hi im trying to use key bind on Tkinter to call this function

def Start():
for i in range(60,-1,-1):
ent['text'] = i
time.sleep(1)
root.update()
ent['text'] = 'Time Out!'
root.update()

i know the function is ok as i have assigned a button and i calls
the function as i expect
but
root.bind('',Start)
gives the following error

Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__
return self.func(*args)
TypeError: Start() takes no arguments (1 given)

Thanks


As the error indicates, the callback function is called with an 
argument, but you don't provide one. That argument is an Event 
instance, so you can get details about the event.


Use

def Start(event):
...

BTW. functions, unlike classes should be all lower-case.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Loop through a dict changing keys

2011-10-15 Thread Alexander Kapps

On 15.10.2011 20:00, Gnarlodious wrote:

What is the best way (Python 3) to loop through dict keys, examine the
string, change them if needed, and save the changes to the same dict?

So for input like this:
{'Mobile': 'string', 'context': '', 'order': '7',
'time': 'True'}

I want to booleanize 'True', turn '7' into an integer, escape
'', and ignore 'string'.

Any elegant Python way to do this?

-- Gnarlie


I think JSON could be of some use, but I've not used it yet, 
otherwise something like this could do it:


#!/usr/bin/python

from cgi import escape

def convert(string):
for conv in (int, lambda x: {'True': True, 'False': False}[x],
 escape):
try:
return conv(string)
except (KeyError, ValueError):
pass
return string


d = {'Mobile': 'string',
 'context': '',
 'order': '7',
 'time': 'True'}

print d

for key in d:
d[key] = convert(d[key])

print d


$ ./conv.py
{'Mobile': 'string', 'order': '7', 'context': '', 
'time': 'True'}
{'Mobile': 'string', 'order': 7, 'context': '', 'time': True}

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


Re: Usefulness of the "not in" operator

2011-10-15 Thread Alexander Kapps

On 10.10.2011 19:29, Nobody wrote:

On Sun, 09 Oct 2011 02:25:27 +0200, Alexander Kapps wrote:


Even if it's off-topic, could you add some similar explanations for
Church numerals (maybe Lambda calculus it isn't too much?)


The Church numeral for N is a function of two arguments which applies its
first argument N times to its second, i.e. (f^N)(x) = f(f(...(f(x))...)).


[SNIP]

Thanks! That's a lot more understandable than Wikipedia. Some 
brain-food for the winter. ;-)

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


How do I get curses to work in Python 3.2 on win-64?

2011-10-15 Thread Jan Sundström
How do I get curses to work in Python 3.2 on win-64?

I'm new to Python and when exploring Python in console I want to use
some
simple functions for console programming that don't emulate a
typewriter
terminal but rather a text screen terminal. I want to be able to clear
the screen, position the cursor
and do unbuffered reading from the keyboard. Also setting different
colors for the text and background.

That could in Windows be accomplished by the handy WConio (http://
newcenturycomputers.net/projects/wconio.html)
which contains just about everything that is needed for a console
application to become useful.

However I want to accomplish it in Python 3.2 because I lack the
experience to build it myself. Now an alternative would
be to use some flavor of curses. Although having a plethora of
unnecessary functions it has the advantage of
existing for different platforms.

I'm currently running Python 3.2.2 on win-64
When Python is installed there is a Python32/Lib/curses library. As I
understand it this is only a some sort of
wrapper for a curses module to be downloaded and installed later??

So I downloaded and installed a curses module I that found and which
seemed appropriate:

curses-2.2.win-amd64-py3.2.exe

from

http://www.lfd.uci.edu/~gohlke/pythonlibs/

It installed some stuff directly in Python32/lib/sitepackages.


Now when I try in a program to do things like:

import curses
stdscr = curses.initscr

Python complains it can't find curses. However if I do

import _curses
stdscr = _curses.initscr

etc., everything works fine. I shouldn't have to write the underscores
though??
How can I fix that?
Should I try to find some other version of curses?

It seems I haven't yet grasped how to install a Python module?

/John

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


Re: Loop through a dict changing keys

2011-10-15 Thread 88888 dihedral
Is there an FAQ available here? Please check the PYTHON official site and the 
active state PYTHON examples first, also check the PLEAC comparisons of a lot 
programming languages first!  

-

Nothing is more thrilling to obtain black magics in text books! 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I search a list for a range of values?

2011-10-15 Thread DevPlayer
On Oct 14, 7:46 pm, Ian Kelly  wrote:
> On Fri, Oct 14, 2011 at 5:36 PM, Troy S  wrote:
> (Python 3)
> date_range = {d:v for d, v in source_dict.items() if '20110809' <= d
> <= '20110911'}
> Ian- Hide quoted text -
> - Show quoted text -

(Python 2.7) supports dictionary comprehensions. I prehaps as early as
2.5.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate error when argument are not supplied and there is no explicit defults (in optparse)?

2011-10-15 Thread ru...@yahoo.com
On 10/14/2011 03:29 PM, Peng Yu wrote:
> Hi,
>
> The following code doesn't give me error, even I don't specify the
> value of filename from the command line arguments. filename gets
> 'None'. I checked the manual, but I don't see a way to let
> OptionParser fail if an argument's value (which has no default
> explicitly specified) is not specified. I may miss some thing in the
> manual. Could any expert let me know if there is a way to do so?
> Thanks!
>
> #!/usr/bin/env python
>
> from optparse import OptionParser
>
> usage = 'usage: %prog [options] arg1 arg2'
> parser = OptionParser(usage=usage)
> parser.set_defaults(verbose=True)
> parser.add_option('-f', '--filename')
>
> #(options, args) = parser.parse_args(['-f', 'file.txt'])
> (options, args) = parser.parse_args()
>
> print options.filename

You can check it yourself.
I find I use a pretty standard pattern with optparse:

 def main (args, opts):
 ...

 def parse_cmdline ():
 p = OptionParser()
 p.add_option('-f', '--filename')
 options, args = parser.parse_args()

 if not options.filename:
p.error ("-f option required")
 if len (args) != 2:
p.error ("Expected exactly 2 arguments")
 # Other checks can obviously be done here too.

 return args, options

 if __name__ == '__main__':
 args, opts = parse_cmdline()
 main (args, opts)

While one can probably subclass OptionParser or use callbacks
to achieve the same end, I find the above approach simple and
easy to follow.

I also presume you know that you have can optparse produce a
usage message by adding 'help' arguments to the add_option()
calls?

And as was mentioned in another post, argparse in Python 2.7
(or in earlier Pythons by downloading/installing it yourself)
can do the checking you want.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I am a newbie for python and try to understand class Inheritance.

2011-10-15 Thread DevPlayer
On Oct 15, 2:20 am, aaabb...@hotmail.com wrote:
> Test.py
> ---
> #!/usr/bin/python
>
> from my_lib import my_function
>
> class MyClass(my_function): # usually class names start capital
>
> """We know you're not forgetting to document."""
>
>     def __init__(self, name):
> super(MyClass, self).__init__(name)
>         # self.name = name automatically added from base class
>
>     def test(self):
>         print "this is a test", self.name
>
> def __call__(self, name):
>
># if you are subclassing something named my_function
># then other Python coders -might- expect the subclass
># to behave like a function.
>
>print "Now this class acts like a function %s" % name
>print "because it has a def __call__(self,...)."
>return True   # not needed but because functions do stuff
>
> If __name__ == '__main__':
>     myclass_instance = MyClass('David') # confusing isn't it to subclass 
> something called my_function

> 
> my_lib.py
> -
> class my_function(object):
>
> """This class acts like a function."""
>
> def __init__(self, name):
> self.name = SpamSpamAndEggs(name)
>
> def __call__(self):
> # do stuff
> return self.name.upper()
> ...
>
> -david

I editted your code to something closer to what is expected.
Not a law but just a recommendation.
Also defining a class my_function(..): --might-- be confusing to
others as in Python there are things called functions that look like
this:

def my_function(name):
print "Hi %s" % name

note the use of "def" and not "class"

Of course if you are making classes that represent custom application
"functions" verse Python "functions" then yeah, calling your class:

class MyFunction(object): ... makes sense

I included the __doc__ "You are documenting" stuff because you seem so
new. Otherwise when posting here they're not expected to be in these
posts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Usefulness of the "not in" operator

2011-10-15 Thread DevPlayer
On Oct 8, 8:41 am, Alain Ketterlin 
wrote:
> candide  writes:
> > Python provides
>
> >     -- the not operator, meaning logical negation
> >     -- the in operator, meaning membership
>
> > On the other hand, Python provides the not in operator meaning
> > non-membership. However, it seems we can reformulate any "not in"
> > expression using only "not" and "in" operation.
>
> Sure, but note that you can also reformulate != using not and ==, <
> using not and >=, etc. Operators like "not in" and "is not" should
> really be considered single tokens, even though they seem to use "not".
> And I think they are really convenient.
>
> -- Alain.

1. I thought "x not in y" was later added as syntax sugar for "not x
in y"
meaning they used the same set of tokens. (Too lazy to check the
actual tokens)

2. "x not in y" ==>> (True if y.__call__(x) else False)
class Y(object):
def __contains__(self, x):
for item in y:
if x == y:
return True
return False

And if you wanted "x not in y" to be a different token you'd have to
ADD

class Y(object):
def __not_contained__(self, x):
for item in self:
if x == y:
return False
return True

AND with __not_contained__() you'd always have to iterate the entire
sequence to make sure even the last item doesn't match.

SO with one token "x not in y" you DON'T have to itterate through the
entire sequence thus it is more effiecient.
-- 
http://mail.python.org/mailman/listinfo/python-list


re: type(), modules: clarification please

2011-10-15 Thread Shane
Hi,

When one writes,

> className='Employee'
> baseClasses = ...
> dictionary = { ... }
> newClass = type( className, , dictionary)

in what module does newClass belong? If it's the current module what
code
do I run to print out the name of that module in a.b.c... form?

Related: If I want to make `newClass' into a module called, say,
a.b.c.d.e
how do I do that? This doesn't work:

> className='a.b.c.d.e.Employee'
> newClass = type( className, , dictionary)

As far as I know the correct procedure involves three steps:
> import a.b.c.d.e as targetModule
> newClass = type( className, , dictionary)
> setattr( targetModule, 'newClassInTarget', newClass )
> obj = targetModule.newClassInTarget()

I am not sure if newClass remains a valid type in whatever module it
was
created in.

Final question. If, as an academic exercise I wanted to recursively
dump
all the classes in a module (and its sub-modules) would I do this? [I
use
some pseudo code]:

def dump( namespace ):
   for i in dir(namespace):
  if i is a class:
   print i
  elif i is a module:
   dump(i)

dump(  )

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


Re: type(), modules: clarification please

2011-10-15 Thread Chris Rebert
On Sat, Oct 15, 2011 at 4:00 PM, Shane  wrote:
> Hi,
>
> When one writes,
>
>> className='Employee'
>> baseClasses = ...
>> dictionary = { ... }
>> newClass = type( className, , dictionary)
>
> in what module does newClass belong? If it's the current module

That does seem to be the case.

> what code
> do I run to print out the name of that module in a.b.c... form?

newClass.__module__ is a string containing the (apparently) qualified
name of the module wherein newClass was defined.


> Final question. If, as an academic exercise I wanted to recursively
> dump
> all the classes in a module (and its sub-modules) would I do this? [I
> use
> some pseudo code]:
>
> def dump( namespace ):
>       for i in dir(namespace):
>              if i is a class:
>                   print i
>              elif i is a module:
>                   dump(i)
>
> dump(  )

Pretty much, though `i` is just a string, so you'll need to use
getattr() to get the actual value of the corresponding variable. You
may also need to watch out for circular references so that your
function doesn't get stuck in an infinite loop.
FYI, `inspect` module had functions to test for class-ness and
module-ness. http://docs.python.org/library/inspect.html

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


Re: Loop through a dict changing keys

2011-10-15 Thread PoD
On Sat, 15 Oct 2011 11:00:17 -0700, Gnarlodious wrote:

> What is the best way (Python 3) to loop through dict keys, examine the
> string, change them if needed, and save the changes to the same dict?
> 
> So for input like this:
> {'Mobile': 'string', 'context': '', 'order': '7',
> 'time': 'True'}
> 
> I want to booleanize 'True', turn '7' into an integer, escape
> '', and ignore 'string'.
> 
> Any elegant Python way to do this?
> 
> -- Gnarlie

How about

data = {
'Mobile': 'string',
'context': '',
'order': '7',
'time': 'True'}
types={'Mobile':str,'context':str,'order':int,'time':bool}

for k,v in data.items():
data[k] = types[k](v)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading a file into a data structure....

2011-10-15 Thread Troy S
Chris,
Thanks for the help.
I am using the powerball numbers from this text file downloaded from the site.
http://www.powerball.com/powerball/winnums-text.txt
The first row is the header/fieldnames and the file starts off like this:

Draw Date   WB1 WB2 WB3 WB4 WB5 PB  PP
10/12/2011  43  10  12  23  47  18  3
10/08/2011  35  03  37  27  45  31  5
10/05/2011  46  07  43  54  20  17  4
10/01/2011  27  43  12  23  01  31  3
09/28/2011  41  51  30  50  53  08  2
09/24/2011  27  12  03  04  44  26  5
09/21/2011  47  52  55  48  12  13  4

The testing of a digit was used to skip the first row only.

I'm stil dissecting your Python code to better understand the use of
collection, namedtuples, etc.
I have not found many examples/descriptions yet about collections,
namedtuples, etc.  I don't quite understand them that much.  Do you
know of a reference that can break this stuff down better for me?
The couple of books that I have on Python do not go into collection,
namedtuples, etc that much.

Thanks,

On Sat, Oct 15, 2011 at 12:47 AM, Chris Rebert  wrote:
> On Fri, Oct 14, 2011 at 7:59 PM, MrPink  wrote:
>> This is what I have been able to accomplish:
>>
>> def isInt(s):
>>    try:
>>        i = int(s)
>>        return True
>>    except ValueError:
>>        return False
>>
>> f = open("powerball.txt", "r")
>> lines = f.readlines()
>> f.close()
>>
>> dDrawings = {}
>> for line in lines:
>>    if isInt(line[0]):
>>        t = line.split()
>>        d = t[0]
>>        month,day,year = t[0].split("/")
>>        i = int(year + month + day)
>>        wb = t[1:6]
>>        wb.sort()
>>        pb = t[6]
>>        r = {'d':d,'wb':wb,'pb':pb}
>>        dDrawings[i] = r
>>
>> The dictionary dDrawings contains records like this:
>> dDrawings[19971101]
>> {'pb': '20', 'd': '11/01/1997', 'wb': ['22', '25', '28', '33', '37']}
>>
>> I am now able to search for ticket in a date range.
>> keys = dDrawings.keys()
>> b = [key for key in keys if 20110909 <= key <= 20111212]
>>
>> How would I search for matching wb (White Balls) in the drawings?
>>
>> Is there a better way to organize the data so that it will be flexible
>> enough for different types of searches?
>> Search by date range, search by pb, search by wb matches, etc.
>>
>> I hope this all makes sense.
>
> from datetime import datetime
> from collections import namedtuple, defaultdict
> # for efficient searching by date: import bisect
>
> DATE_FORMAT = "%m/%d/%Y"
> Ticket = namedtuple('Ticket', "white_balls powerball date".split())
>
> powerball2ticket = defaultdict(set)
> whiteball2ticket = defaultdict(set)
> tickets_by_date = []
>
> with open("powerball.txt", "r") as f:
>    for line in f:
>        if not line[0].isdigit():
>            # what are these other lines anyway?
>            continue # skip such lines
>
>        fields = line.split()
>
>        date = datetime.strptime(fields[0], DATE_FORMAT).date()
>        white_balls = frozenset(int(num_str) for num_str in fields[1:6])
>        powerball = int(fields[6])
>        ticket = Ticket(white_balls, powerball, date)
>
>        powerball2ticket[powerball].add(ticket)
>        for ball in white_balls:
>            whiteball2ticket[ball].add(ticket)
>        tickets_by_date.append(ticket)
>
> tickets_by_date.sort(key=lambda ticket: ticket.date)
>
> print(powerball2ticket[7]) # all tickets with a 7 powerball
> print(whiteball2ticket[3]) # all tickets with a non-power 3 ball
>
>
> Cheers,
> Chris
> --
> http://rebertia.com
>



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


Re: Reading a file into a data structure....

2011-10-15 Thread MrPink
I did not understand what a tuple was.
So it was very hard for me to understand what a namedtuple was and
follow the code.
Then I looked up the word at dictionary.com and got this:
http://dictionary.reference.com/browse/tuple

tuple:  computing  a row of values in a relational database

Now I understand a little better what a tuple is and can follow the
code better.

A namedtuple seems like a dictionary type.  I'll need to read up on
the difference between the two.

Thanks again.

On Oct 15, 12:47 am, Chris Rebert  wrote:
> On Fri, Oct 14, 2011 at 7:59 PM,MrPink wrote:
> > This is what I have been able to accomplish:
>
> > def isInt(s):
> >    try:
> >        i = int(s)
> >        return True
> >    except ValueError:
> >        return False
>
> > f = open("powerball.txt", "r")
> > lines = f.readlines()
> > f.close()
>
> > dDrawings = {}
> > for line in lines:
> >    if isInt(line[0]):
> >        t = line.split()
> >        d = t[0]
> >        month,day,year = t[0].split("/")
> >        i = int(year + month + day)
> >        wb = t[1:6]
> >        wb.sort()
> >        pb = t[6]
> >        r = {'d':d,'wb':wb,'pb':pb}
> >        dDrawings[i] = r
>
> > The dictionary dDrawings contains records like this:
> > dDrawings[19971101]
> > {'pb': '20', 'd': '11/01/1997', 'wb': ['22', '25', '28', '33', '37']}
>
> > I am now able to search for ticket in a date range.
> > keys = dDrawings.keys()
> > b = [key for key in keys if 20110909 <= key <= 20111212]
>
> > How would I search for matching wb (White Balls) in the drawings?
>
> > Is there a better way to organize the data so that it will be flexible
> > enough for different types of searches?
> > Search by date range, search by pb, search by wb matches, etc.
>
> > I hope this all makes sense.
>
> from datetime import datetime
> from collections import namedtuple, defaultdict
> # for efficient searching by date: import bisect
>
> DATE_FORMAT = "%m/%d/%Y"
> Ticket = namedtuple('Ticket', "white_balls powerball date".split())
>
> powerball2ticket = defaultdict(set)
> whiteball2ticket = defaultdict(set)
> tickets_by_date = []
>
> with open("powerball.txt", "r") as f:
>     for line in f:
>         if not line[0].isdigit():
>             # what are these other lines anyway?
>             continue # skip such lines
>
>         fields = line.split()
>
>         date = datetime.strptime(fields[0], DATE_FORMAT).date()
>         white_balls = frozenset(int(num_str) for num_str in fields[1:6])
>         powerball = int(fields[6])
>         ticket = Ticket(white_balls, powerball, date)
>
>         powerball2ticket[powerball].add(ticket)
>         for ball in white_balls:
>             whiteball2ticket[ball].add(ticket)
>         tickets_by_date.append(ticket)
>
> tickets_by_date.sort(key=lambda ticket: ticket.date)
>
> print(powerball2ticket[7]) # all tickets with a 7 powerball
> print(whiteball2ticket[3]) # all tickets with a non-power 3 ball
>
> Cheers,
> Chris
> --http://rebertia.com

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


Re: argparse zero-length switch

2011-10-15 Thread Carl Banks
On Friday, October 14, 2011 12:41:26 AM UTC-7, Peter Otten wrote:
> Carl Banks wrote:
> 
> > Is it possible to specify a zero-length switch?  Here's what I mean.
> > 
> > I have a use case where some users would have to enter a section name on
> > the command line almost every time, whereas other users (the ones using
> > only one section) will never have to enter the section name.  I don't want
> > to burden users with only one "section" to always enter the section name
> > as a required argument, but I also want to make it as convenient as
> > possible to enter the section name for those who need to.
> > 
> > My thought, on the thinking that practicality beats purity, was to create
> > a zero-length switch using a different prefix character (say, @) to
> > indicate the section name.  So instead of typing this:
> > 
> >sp subcommand -s abc foo bar
> > 
> > they could type this:
> > 
> >sp subcommand @abc foo bar
> > 
> > Admittedly a small benefit.  I tried the following but argparse doesn't
> > seem to do what I'd hoped:
> > 
> >p = argparse.ArgumentParser(prefix_chars='-@')
> >p.add_argument('@',type=str,dest='section')
> >ar = p.parse_args(['@abc'])
> > 
> > This throws an exception claiming unrecognized arguments.
> > 
> > Is there a way (that's not a hack) to do this?  Since the current behavior
> > of the above code seems to do nothing useful, it could be added to
> > argparse with very low risk of backwards incompatibility.
> 
> If the number of positional arguments is otherwise fixed you could make 
> section a positional argument with nargs="?"

The positional arguments aren't fixed, otherwise I would have done it that way. 
 I ended up deciding to prescan the command line for arguments starting with @, 
and that actually has some benefits over doing it with argparse.  (One little 
surprise is if you pass it something like "-x @abc foo", where foo is the 
argument of -x.)

I don't really care for or agree with Steven and Ben Finney's foolish 
consistency.  I already weighed it against the benefits of consistency, and 
decided that this parameter was easily important enough to warrant special 
treatment.  It's actually a good thing for this parameter to look different 
from other switches; it marks it as specially important.


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


Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-15 Thread Carl Banks
On Friday, October 14, 2011 6:23:15 PM UTC-7, alex23 wrote:
> On Oct 14, 4:56 pm, Carl Banks 
>  wrote:
> > But you can see that, fully realized, syntax like that can do much more
> > than can be done with library code.
> 
> Well sure, but imaginary syntax can do _anything_. That doesn't mean
> it's possible within CPython.

Hey, thanks for backing me up on that sentiment.  :)


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


Re: argparse zero-length switch

2011-10-15 Thread Chris Angelico
On Sun, Oct 16, 2011 at 2:29 PM, Carl Banks  wrote:
> I don't really care for or agree with Steven and Ben Finney's foolish 
> consistency.  I already weighed it against the benefits of consistency, and 
> decided that this parameter was easily important enough to warrant special 
> treatment.  It's actually a good thing for this parameter to look different 
> from other switches; it marks it as specially important.

I'll weigh in then - in favour of the "foolish" consistency. It's a
far more valuable feature than you might imagine. Think how much time
your users (even yourself) are going to spend using your program; now
think how much time those same people will spend using other programs.
You can't fight something that's orders of magnitude bigger than you,
so what you'll be doing is creating a special-case that has to be kept
in the user's mind. You'll also run into trouble if anyone has a file
name that begins @; this situation already exists, but I think most
people know not to create a file called "-rf" (and even then, most
Unix programs accept "--" to mean "end of options, the next thing is a
filename").

Do what everyone else does. You'll thank yourself for it in a year or so.

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


Re: Usefulness of the "not in" operator

2011-10-15 Thread Steven D'Aprano
On Sat, 15 Oct 2011 15:04:24 -0700, DevPlayer wrote:

> 1. I thought "x not in y" was later added as syntax sugar for "not x in
> y"
> meaning they used the same set of tokens. (Too lazy to check the actual
> tokens)

Whether the compiler has a special token for "not in" is irrelevant. 
Perhaps it uses one token, or two, or none at all because a pre-processor 
changes "x not in y" to "not x in y". That's an implementation detail. 
What's important is whether it is valid syntax or not, and how it is 
implemented.

As it turns out, the Python compiler does not distinguish the two forms:

>>> from dis import dis
>>> dis(compile('x not in y', '', 'single'))
  1   0 LOAD_NAME0 (x)
  3 LOAD_NAME1 (y)
  6 COMPARE_OP   7 (not in)
  9 PRINT_EXPR  
 10 LOAD_CONST   0 (None)
 13 RETURN_VALUE
>>> dis(compile('not x in y', '', 'single'))
  1   0 LOAD_NAME0 (x)
  3 LOAD_NAME1 (y)
  6 COMPARE_OP   7 (not in)
  9 PRINT_EXPR  
 10 LOAD_CONST   0 (None)
 13 RETURN_VALUE


Also for what it is worth, "x not in y" goes back to at least Python 1.5, 
and possibly even older. (I don't have any older versions available to 
test.)



> 2. "x not in y" ==>> (True if y.__call__(x) else False) 

y.__call__ is irrelevant. But for what it's worth:

(1) Instead of writing "y.__call__(x)", write "y(x)"

(2) Instead of writing "True if blah else False", write "bool(blah)".


> class Y(object):
> def __contains__(self, x):
> for item in y:
> if x == y:
> return True
> return False

You don't have to define a __contains__ method if you just want to test 
each item sequentially. All you need is to obey the sequence protocol and 
define a __getitem__ that works in the conventional way:


>>> class Test:
... def __init__(self, args):
... self._data = list(args)
... def __getitem__(self, i):
... return self._data[i]
... 
>>> t = Test("abcde")
>>> "c" in t
True
>>> "x" in t
False

Defining a specialist __contains__ method is only necessary for non-
sequences, or if you have some fast method for testing whether an item is 
in the object quickly. If all you do is test each element one at a time, 
in numeric order, don't bother writing __contains__.


> And if you wanted "x not in y" to be a different token you'd have to ADD

Tokens are irrelevant. "x not in y" is defined to be the same as "not x 
in y" no matter what. You can't define "not in" to do something 
completely different.


> class Y(object):
> def __not_contained__(self, x):
> for item in self:
> if x == y:
> return False
> return True
> 
> AND with __not_contained__() you'd always have to iterate the entire
> sequence to make sure even the last item doesn't match.
> 
> SO with one token "x not in y" you DON'T have to itterate through the
> entire sequence thus it is more effiecient.

That's not correct.




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


Re: How do I get curses to work in Python 3.2 on win-64?

2011-10-15 Thread Christoph Gohlke
On Oct 15, 1:13 pm, Jan Sundström  wrote:
> How do I get curses to work in Python 3.2 on win-64?
>
> I'm new to Python and when exploring Python in console I want to use
> some
> simple functions for console programming that don't emulate a
> typewriter
> terminal but rather a text screen terminal. I want to be able to clear
> the screen, position the cursor
> and do unbuffered reading from the keyboard. Also setting different
> colors for the text and background.
>
> That could in Windows be accomplished by the handy WConio (http://
> newcenturycomputers.net/projects/wconio.html)
> which contains just about everything that is needed for a console
> application to become useful.
>
> However I want to accomplish it in Python 3.2 because I lack the
> experience to build it myself. Now an alternative would
> be to use some flavor of curses. Although having a plethora of
> unnecessary functions it has the advantage of
> existing for different platforms.
>
> I'm currently running Python 3.2.2 on win-64
> When Python is installed there is a Python32/Lib/curses library. As I
> understand it this is only a some sort of
> wrapper for a curses module to be downloaded and installed later??
>
> So I downloaded and installed a curses module I that found and which
> seemed appropriate:
>
> curses-2.2.win-amd64-py3.2.exe
>
> from
>
> http://www.lfd.uci.edu/~gohlke/pythonlibs/
>
> It installed some stuff directly in Python32/lib/sitepackages.
>
> Now when I try in a program to do things like:
>
> import curses
> stdscr = curses.initscr
>
> Python complains it can't find curses. However if I do
>
> import _curses
> stdscr = _curses.initscr
>
> etc., everything works fine. I shouldn't have to write the underscores
> though??
> How can I fix that?
> Should I try to find some other version of curses?
>
> It seems I haven't yet grasped how to install a Python module?
>
> /John

`import curses` should work. What exactly is the error message? Does
`import curses` work outside your program/program directory?

The curses package is part of the standard library and usually
installed in Python32\Lib\curses. On Windows the  _curses.pyd files is
missing in the standard distribution. curses-2.2.win-amd64-py3.2.exe
installs the missing _curses.pyd file into Lib/site-packages.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: argparse zero-length switch

2011-10-15 Thread Steven D'Aprano
On Sat, 15 Oct 2011 20:29:40 -0700, Carl Banks wrote:

> I don't really care for or agree with Steven and Ben Finney's foolish
> consistency.  I already weighed it against the benefits of consistency,
> and decided that this parameter was easily important enough to warrant
> special treatment.  It's actually a good thing for this parameter to
> look different from other switches; it marks it as specially important.

It seems to me that a parameter hardly deserves to be called "specially 
important" if it is optional and the user can leave it out. "Specially 
unimportant" is probably a better description.

At the end of the day, your claimed motivation for inventing this anti-
mnemonic was, and I quote, "to make it as convenient as possible to enter 
the section name". If you honestly think that typing shift-2 is more 
convenient than typing -s then go right ahead and do what you like. No 
skin off my nose.


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


Re: SciPy/NumPy: read, write images using Python3

2011-10-15 Thread Christoph Gohlke
On Oct 9, 8:43 am, thegripper  wrote:
> In SciPy / NumPy, the primary way to read and write images is PIL. But
> PIL does not yet support Python3. Is there some good way to read,
> write, and resize images in a NumPy and Python3 environment?

Try Scikits.image . It uses a plugin system
to read/write images to/from numpy arrays via FreeImage, PyQt, FITS,
GDAL, etc.

Other options:

Unofficial PIL ports, e.g.  or


PythonMagick 

GDAL  for raster geospatial data formats

PyGame 1.9.2pre , uses SDL_image

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


Re: argparse zero-length switch

2011-10-15 Thread Gregory Ewing

Steven D'Aprano wrote:


And it isn't like you gain any extra clarity or expressiveness, or even a
major saving of typing! "-s" vs "@". You don't even save a key stroke: "@"
requires two keystrokes, just as "-s" does.


Also keep in mind that not all keystrokes are equal. Someone
who uses all their fingers probably finds "-s" faster and
easier to type than "@". I certainly do.

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