Re: [Tutor] pure function problem

2010-09-23 Thread Roelof Wobben




> From: st...@pearwood.info
> To: tutor@python.org
> Date: Fri, 24 Sep 2010 13:00:40 +1000
> Subject: Re: [Tutor] pure function problem
>
> Roelof, please learn to delete unnecessarily quoted text. There's no
> need to quoted the entire discussion every time you answer.
>
> On Fri, 24 Sep 2010 06:20:25 am Roelof Wobben wrote:
>
>> time = tijd()
> [...]
>> print time(uitkomst)
>
> Why are you calling time as a function, when it is a tijd instance?
>
>
>
>
> --
> Steven D'Aprano
> ___
> Tutor maillist - Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 
 
Hello Steve,
 
I found this in my tutorial.
 
13.8. Instances as return values¶
Functions can return instances. For example, find_center takes a Rectangle as 
an argument and returns a Point that contains the coordinates of the center of 
the Rectangle:
def find_center(box):
p = Point()
p.x = box.corner.x + box.width/2.0
p.y = box.corner.y - box.height/2.0
return p
To call this function, pass box as an argument and assign the result to a 
variable:
>>> center = find_center(box)
>>> print_point(center)
(50.0, 100.0)

 
So i followed it but appearently not the good way.
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pure function problem

2010-09-23 Thread Steven D'Aprano
Roelof, please learn to delete unnecessarily quoted text. There's no 
need to quoted the entire discussion every time you answer.

On Fri, 24 Sep 2010 06:20:25 am Roelof Wobben wrote:

> time = tijd()
[...]
> print time(uitkomst)

Why are you calling time as a function, when it is a tijd instance?




-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Plotting a Linear Equation

2010-09-23 Thread Corey Richardson

 Hello tutors. Probably the wrong mailing list, but someone might know.
I want to use matplotlib (or similar) to plot an equation in 
slope-intercept (y=mx+b) or standard form (Ax + By = C). As far as I've 
read and tested, you can only plot with a series of points. I could make 
two points out of those manually, but I was wondering if anyone knew of 
an easier way. Thanks.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dict of function calls

2010-09-23 Thread Steven D'Aprano
On Fri, 24 Sep 2010 01:45:29 am you wrote:
> > Oh, and (4)... in Python circles, it's traditional but not
> > compulsory to use metasyntactic variables named after Monty Python
> > sketches rather than foo and bar. So spam, ham, eggs, parrot (dead
> > or otherwise), names of cheeses, aardvark..., although there is no
> > standard order.
>
> Hm, someone maybe should update http://en.wikipedia.org/wiki/Foobar
> ... as there is a python example listed there...

If only Wikipedia was an encyclopedia anyone can edit!

*wink*



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] functions: use return or exceptions?

2010-09-23 Thread Steven D'Aprano
On Fri, 24 Sep 2010 05:32:55 am Alex Hall wrote:
> Hi all,
> A general coding question: is it better to use return(False) (or 0,
> or -1, or whatever) or to raise whateverError("oops")? Are there
> cases for each?

Yes.

There is absolutely no point whatsoever raising an exception, or 
returning a "magic" sentinel value, if an ordinary value would do. For 
example, this would be silly:


def is_spam(string):
"""Return True if string equals "spam", otherwise 
raise an exception."""
if string.lower().strip() == "spam":
return True
raise ValueError("not spam")


If is_spam can only ever return True, there's no need to look at the 
return result. So why bother to return anything? This would be better:

def verify_spam(string):
"""Raise ValueError unless string is spam."""
if string.lower().strip() != "spam":
raise ValueError("not spam")

(Technically, this will return None, but that's just because Python 
doesn't have procedures, only functions.)

This is appropriate if your use-case is something like this:

def prepare_meal(meat, condiments):
"""Prepare a yummy meal from the only meat-like substance 
worth eating."""
verify_spam(meat)
if "pickle" in condiments:
# I don't like pickle
condiments.remove("pickle")
# but I do like spam
condiments.append("mashed spam")
return "spam" + spread(condiments, meat) + "spam spam spam"


On the other hand, returning True or False would be better if your 
use-case was like this:

def prepare_meal(meat, condiments):
"""Prepare a yummy meal."""
if is_spam(meat):
vikings.sing("spam spam spam LOVELY SPAM!!!")
if "pickle" in condiments:
condiments.remove("pickle")
return "bread" + spread(condiments, meat) + "bread"



A good guide is to look at what functions in the standard library do. 
You'll find examples of functions that return a magic value or raise an 
exception:

"ethel the aardvark".find('spam')
=> -1

"ethel the aardvark".index('spam')
=> raises exception

Of course, functions should generally raise exceptions for errors:

"ethel the aardvark".find(42)
=> raises exception

There are very few places in Python that suppress and hide arbitrary 
errors from the user. This should be done with care, if at all.


-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] functions: use return or exceptions?

2010-09-23 Thread Steven D'Aprano
On Fri, 24 Sep 2010 05:47:21 am Wayne Werner wrote:

> OTOH, a lot of people feel that using exceptions as control flow is
> bad practice - they're exceptional so they should only arise in
> exceptional case.

That's not the Python philosophy. Python uses exceptions for flow 
control: iteration catching StopIteration is just the most common 
example. There's nothing wrong with using exceptions in your own code 
for the same purpose.

Note carefully that exceptions *cannot* be used to implement 
unstructured GOTOs, since you can't jump into the middle of a function, 
or backwards.

Speaking of GOTO, and it's even more evil cousin COME FROM, see this 
wonderful April 1st joke:

http://mail.python.org/pipermail/python-announce-list/2004-April/002982.html


> There may be performance issues, though I'm not familiar enough with
> that yet.

Setting up a try...except block is fast, about as fast as the "pass" 
statement. "Do nothing" is about as fast as you can get in Python, so 
you need not fear wrapping things in a try block.

But catching an exception is about 100 times more expensive. If you're 
using *lots* of exceptions for flow control, then your code will 
probably be slow. A single exception to end the flow, like 
StopIteration, doesn't matter.



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] __import__()

2010-09-23 Thread Emile van Sebille

On 9/23/2010 8:26 AM Pete said...

Hiya,

still working on my plugin architecture. I figured out how to import modules of 
which I don't know the name yet at compile time,
by using __import__() instead of import.

So that works fine when I want to have the equivalent of

import spam

... by using

__import__('spam')

Question:

what is the equivalent of

from spam import *


Something you probably really don't want to do as it will pollute your 
namespace. But, if you insist, you could play with:


ActivePython 2.6.1.1 (ActiveState Software Inc.) based on
Python 2.6.1 (r261:67515, Dec  5 2008, 13:58:38)
[MSC v.1500 32 bit (Intel)] on win32
>>> xx = __import__('httplib')
>>> dir(xx)
['ACCEPTED', 'BAD_GATEWAY', ...]

>>> for ii in dir(xx): globals()[ii] = xx.__dict__[ii]
...
>>> dir()
['ACCEPTED', 'BAD_GATEWAY', ...]
>>>

Note, this really is for consenting adults only, and changing globals() 
is not really supported and may change in the future.  Note that from 
the docs, globals() is defined to "Return a dictionary representing the 
current global symbol table" and not as "Return the dictionary holding 
the current global symbol table" so the fact that it works on may 
version (and perhaps all others) doesn't mean it'll work everywhere.


HTH,

Emile









































___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] functions: use return or exceptions?

2010-09-23 Thread Steven D'Aprano
On Fri, 24 Sep 2010 06:06:25 am Luke Paireepinart wrote:
> You should do both. Raise an exception in the exceptional case.
>
> My general pattern is to return None if no results exist, return the
> results if they do exist, and raise an exception if I couldn't
> perform the function.

I hate that! I find that idiom, as used by the re module, to be the 
worst of all possible worlds.

To do something with a search result, you have to:

be prepared for an exception (either catch it, or let it bubble up the 
call chain);

if you get a result, you have to compare it to None and be prepared to 
ignore it;

if the result isn't None, then you can do something with it. This itself 
may include further tests or catching exceptions.

At the interactive interpreter, you can't write (say):

regex.search(text).group()

because the result is sometimes None. So you have to split it into two 
operations:

mo = regex.search(text)
if mo: mo.group()

That's a nuisance when working interactively. I would prefer it if the 
re search functions returned a "blank" match object, so you could say:


re.search('sp.m', 'I like spam and eggs').group(0)
=> prints 'spam'

re.search('sp.m', 'I like ham and eggs').group(0)
=> prints ''


> Eg. If I have a function that creates a list of users with a first
> name of bob, I'll return the users or None (or probably an empty
> list) 

Returning an empty list makes sense. Returning None makes no sense at 
all.


> but if the db connection is unsuccessful I'll let the exception 
> it throws propagate back up from my function, or possibly trap and
> rethrow the exception.

That's okay.


> Or if a db connection error shouldn't matter to the calling function,
> I just won't re raise the exception.

That's a reasonable approach as well.




-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] functions: use return or exceptions?

2010-09-23 Thread Alex Hall
Thanks for the responses. Up to now, despite using some Java and a lot
of Python, I have not even tried raising exceptions. I can see
situations where they would be useful, but was not sure if I should
use them as much as possible or just keep relying on the return codes
that I am used to. Sounds like either way works and, as was stated,
exceptions should be used in "exceptional" cases.

On 9/23/10, Luke Paireepinart  wrote:
> You should do both. Raise an exception in the exceptional case.
>
> My general pattern is to return None if no results exist, return the results
> if they do exist, and raise an exception if I couldn't perform the function.
>
> Eg. If I have a function that creates a list of users with a first name of
> bob, I'll return the users or None (or probably an empty list) but if the db
> connection is unsuccessful I'll let the exception it throws propagate back
> up from my function, or possibly trap and rethrow the exception.
>
> Or if a db connection error shouldn't matter to the calling function, I just
> won't re raise the exception.
>
> I may not actually do that in practice, depending on the implications, but
> that's my general idea usually.
>
> -
> Sent from a mobile device with a bad e-mail client.
> -
>
> On Sep 23, 2010, at 2:47 PM, Wayne Werner  wrote:
>
>> On Thu, Sep 23, 2010 at 2:32 PM, Alex Hall  wrote:
>> Hi all,
>> A general coding question: is it better to use return(False) (or 0, or
>> -1, or whatever) or to raise whateverError("oops")? Are there cases
>> for each?
>>
>> It depends on your prevailing philosophy - if you like the EAFP that
>> prevails in python, it's better to raise an error. Usually that indicates
>> that something has failed.
>>
>> OTOH, a lot of people feel that using exceptions as control flow is bad
>> practice - they're exceptional so they should only arise in exceptional
>> case.
>>
>> There may be performance issues, though I'm not familiar enough with that
>> yet.
>>
>> just my two bits,
>> -Wayne
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Test Drive Development, DocTest, UnitTest

2010-09-23 Thread Tino Dai
> The lines between doc tests, blackbox testing, whitebox testing, and
> regression testing is blurry. People may legitimately disagree on
> whether a specific test is documentation, testing the interface,
> testing the implementation, or all three.
>

Wow!!! Ok that clears up a lot. Thank you
Just to clear some things up:

Internal == doctest
External == blackbox testng (using unit tests)

Thanks again! Now off to go write some doctests and unit tests! :)
-Tino
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pure function problem

2010-09-23 Thread Roelof Wobben




> From: rwob...@hotmail.com
> To: tutor@python.org
> Subject: RE: [Tutor] pure function problem
> Date: Thu, 23 Sep 2010 10:15:07 +
>
>
>
>> Date: Thu, 23 Sep 2010 05:36:58 -0400
>> Subject: Re: [Tutor] pure function problem
>> From: jemejo...@gmail.com
>> To: tutor@python.org
>> CC: rwob...@hotmail.com
>>
>> The problem is that your class definition doesn't do anything to
>> explicitly set those attributes.
>>
>> On Thu, Sep 23, 2010 at 4:58 AM, Roelof Wobben wrote:
>>
>>> class tijd :
>>> pass
>>
>> You're not doing any explicit setting of attributes at the class level.
>>
>>
>>> time = tijd()
>>> time.hour = 20
>>> time.minutes = 20
>>> time.seconds = 20
>>
>> You set them on this instance.
>>
>>> seconds = 20
>>> uitkomst = tijd()
>>
>> But not on this one.
>>
>> What you probably want to do is something like this:
>>
>> class tijd(object):
>> def __init__(self):
>> self.hour = 20
>> self.minutes = 20
>> self.seconds = 20
>>
>> Or if you prefer to set these when you create the instance, you can
>> pass in values like this:
>>
>> class tijd(object):
>> def __init__(self, hour=20, minutes=20, seconds=20):
>> self.hour = hour
>> self.minutes = minutes
>> self.seconds = seconds
>>
>> I noticed something odd just a sec ago. You have this:
>>> uitkomst = tijd()
>>> uitkomst = increment(time, seconds)
>>> print uitkomst.minutes, uitkomst.seconds
>>
>> You're creating a tijd instance, binding uitkomst to it, then
>> overwriting that instance with what you return from increment().
>>
>> Anyway, hth.
>>
>> - jmj
>
>
> Correct,
>
> I try to find a way to solve this error message.
>
> Roelof
>

 
Oke, 
 
I changed everything to this : 
 
class tijd :
pass
 
def increment(time, seconds):
sum = tijd()
sum.seconds = time.seconds + seconds 

if sum.seconds> 60 :
minutes, seconds = divmod(sum.seconds, 60)
sum.seconds = seconds 
sum.minutes = time.minutes + minutes
return sum
 
time = tijd()
time.hour = 20 
time.minutes = 20
time.seconds = 20 
seconds = 20
uitkomst = increment(time, seconds)
print time(uitkomst)
 
But now Im getting this error message :
 
Traceback (most recent call last):
  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 21, in 
print time(uitkomst)
AttributeError: tijd instance has no __call__ method
 
 
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] functions: use return or exceptions?

2010-09-23 Thread Luke Paireepinart
You should do both. Raise an exception in the exceptional case.

My general pattern is to return None if no results exist, return the results if 
they do exist, and raise an exception if I couldn't perform the function.

Eg. If I have a function that creates a list of users with a first name of bob, 
I'll return the users or None (or probably an empty list) but if the db 
connection is unsuccessful I'll let the exception it throws propagate back up 
from my function, or possibly trap and rethrow the exception.

Or if a db connection error shouldn't matter to the calling function, I just 
won't re raise the exception.

I may not actually do that in practice, depending on the implications, but 
that's my general idea usually.

-
Sent from a mobile device with a bad e-mail client.
-

On Sep 23, 2010, at 2:47 PM, Wayne Werner  wrote:

> On Thu, Sep 23, 2010 at 2:32 PM, Alex Hall  wrote:
> Hi all,
> A general coding question: is it better to use return(False) (or 0, or
> -1, or whatever) or to raise whateverError("oops")? Are there cases
> for each?
> 
> It depends on your prevailing philosophy - if you like the EAFP that prevails 
> in python, it's better to raise an error. Usually that indicates that 
> something has failed.
> 
> OTOH, a lot of people feel that using exceptions as control flow is bad 
> practice - they're exceptional so they should only arise in exceptional case.
> 
> There may be performance issues, though I'm not familiar enough with that yet.
> 
> just my two bits,
> -Wayne
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] functions: use return or exceptions?

2010-09-23 Thread Wayne Werner
On Thu, Sep 23, 2010 at 2:32 PM, Alex Hall  wrote:

> Hi all,
> A general coding question: is it better to use return(False) (or 0, or
> -1, or whatever) or to raise whateverError("oops")? Are there cases
> for each?


It depends on your prevailing philosophy - if you like the EAFP that
prevails in python, it's better to raise an error. Usually that indicates
that something has failed.

OTOH, a lot of people feel that using exceptions as control flow is bad
practice - they're exceptional so they should only arise in exceptional
case.

There may be performance issues, though I'm not familiar enough with that
yet.

just my two bits,
-Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] functions: use return or exceptions?

2010-09-23 Thread Alex Hall
Hi all,
A general coding question: is it better to use return(False) (or 0, or
-1, or whatever) or to raise whateverError("oops")? Are there cases
for each?

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Windows Printing, Round 2

2010-09-23 Thread Tim Golden

On 23/09/2010 7:18 PM, Rance Hall wrote:

Again I'm referencing Tim Golden from

http://timgolden.me.uk/python/win32_how_do_i/print.html


This code block is relevant:



import os, sys
import win32print
printer_name = win32print.GetDefaultPrinter ()
#
# raw_data could equally be raw PCL/PS read from
#  some print-to-file operation
#
if sys.version_info>= (3,):
   raw_data = bytes ("This is a test", "utf-8")
else:
   raw_data = "This is a test"

hPrinter = win32print.OpenPrinter (printer_name)
try:
   hJob = win32print.StartDocPrinter (hPrinter, 1, ("test of raw data",
None, "RAW"))
   try:
 win32print.WritePrinter (hPrinter, raw_data)
   finally:
 win32print.EndDocPrinter (hPrinter)
finally:
   win32print.ClosePrinter (hPrinter)





Things are progressing along and I'm really more and more excited
about python, every time I try to do something, It just seems to work
and be straightforward.

Notes:  AFAICS win32pring.StartDocPrinter(hPrinter, 1, (jobname, None,
None)) might be better as the last "None" tells the system to process
through the print driver, Raw Data bypasses the print driver.
Due to the variety of printers involved, I think bypassing the print
driver with "RAW" will come back and bite me later.

I also added a variable to catch the output from
win32print.WritePrinter() so it would not display on the screen.  I
called it hSize.

Questions:

Under python 3 I need to send a byte string to the printer.  But I
wont have a byte string, I'll have a filename

What is the pythonic way to convert a file to a bytestream?

I can open the file for reading, and loop line by line through the
file appending bytes(line, "utf-8") to variable but this doesn't seem
right to me somehow.

Is there a better way to do this?


My HP laserjet 1100 does not print the job automatically.  It accepts
the job, processes the job, and then lights up the lights on the front
of the printer and waits.  When I hit the button, then the document
prints.

I have only seen this behavior before when printing envelopes.  When
an envelope print job goes to the printer it behaves the same way my
python print jobs are.

I suspect that this has to do with the fact that the page size of the
printjob is either not specified or different from the standard 8.5 in
wide x 11 in long it can handle.

win32print documentation mentions DocumentProperties and
DeviceCapabilities that might help, but I don't see how to use them to
implement a solution for my problem.

I further suspect that there are other printers out there that will
behave similarly if they don't have specified what they needed.

How do you deal with this problem?


Essentially the complexity of the answer to this question -- the big
gap between raw (textish) data and any other formatted output -- was
what prompted my earlier suggestion to use IE as a print engine.

An easy answer to your questions above would be:

send the file's byte contents (see snippet below) followed by a formfeed
to prompt the printer into actually doing something.


import os, sys
import win32print
printer_name = win32print.GetDefaultPrinter ()  # for simplicity

raw_data = open ("filename.txt", "rb").read () + b"\x0c"

# OpenPrinter / ClosePrinter dance as above



Does that help?

TJG
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Windows Printing, Round 2

2010-09-23 Thread Rance Hall
Again I'm referencing Tim Golden from

http://timgolden.me.uk/python/win32_how_do_i/print.html


This code block is relevant:



import os, sys
import win32print
printer_name = win32print.GetDefaultPrinter ()
#
# raw_data could equally be raw PCL/PS read from
#  some print-to-file operation
#
if sys.version_info >= (3,):
  raw_data = bytes ("This is a test", "utf-8")
else:
  raw_data = "This is a test"

hPrinter = win32print.OpenPrinter (printer_name)
try:
  hJob = win32print.StartDocPrinter (hPrinter, 1, ("test of raw data",
None, "RAW"))
  try:
win32print.WritePrinter (hPrinter, raw_data)
  finally:
win32print.EndDocPrinter (hPrinter)
finally:
  win32print.ClosePrinter (hPrinter)





Things are progressing along and I'm really more and more excited
about python, every time I try to do something, It just seems to work
and be straightforward.

Notes:  AFAICS win32pring.StartDocPrinter(hPrinter, 1, (jobname, None,
None)) might be better as the last "None" tells the system to process
through the print driver, Raw Data bypasses the print driver.
Due to the variety of printers involved, I think bypassing the print
driver with "RAW" will come back and bite me later.

I also added a variable to catch the output from
win32print.WritePrinter() so it would not display on the screen.  I
called it hSize.

Questions:

Under python 3 I need to send a byte string to the printer.  But I
wont have a byte string, I'll have a filename

What is the pythonic way to convert a file to a bytestream?

I can open the file for reading, and loop line by line through the
file appending bytes(line, "utf-8") to variable but this doesn't seem
right to me somehow.

Is there a better way to do this?


My HP laserjet 1100 does not print the job automatically.  It accepts
the job, processes the job, and then lights up the lights on the front
of the printer and waits.  When I hit the button, then the document
prints.

I have only seen this behavior before when printing envelopes.  When
an envelope print job goes to the printer it behaves the same way my
python print jobs are.

I suspect that this has to do with the fact that the page size of the
printjob is either not specified or different from the standard 8.5 in
wide x 11 in long it can handle.

win32print documentation mentions DocumentProperties and
DeviceCapabilities that might help, but I don't see how to use them to
implement a solution for my problem.

I further suspect that there are other printers out there that will
behave similarly if they don't have specified what they needed.

How do you deal with this problem?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dict of function calls

2010-09-23 Thread Pete
> Oh, and (4)... in Python circles, it's traditional but not compulsory 
> to use metasyntactic variables named after Monty Python sketches 
> rather than foo and bar. So spam, ham, eggs, parrot (dead or 
> otherwise), names of cheeses, aardvark..., although there is no 
> standard order.

Hm, someone maybe should update http://en.wikipedia.org/wiki/Foobar
... as there is a python example listed there...

- Pete
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] __import__()

2010-09-23 Thread Pete
Hiya,

still working on my plugin architecture. I figured out how to import modules of 
which I don't know the name yet at compile time,
by using __import__() instead of import.

So that works fine when I want to have the equivalent of 

import spam

... by using

__import__('spam')

Question:

what is the equivalent of

from spam import *

?

thanks,

Pete
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Windows printing

2010-09-23 Thread Tim Golden

On 23/09/2010 14:05, Rance Hall wrote:

For the first roll-out and testing I figured plaintext was good enough.

Future revisions will probably use the PDF library you also referred
to on your page.

Either way that is as printer ready as I expect I will be able to get it.


One option you might want to consider is to use IE as a print
engine. Here's some code I use to print stuff via IE, converting
it to HTML via Pygments. (Handy for printing Python code).

Obviously you could skip the conversion step and just format your
ticket as HTML in the normal way. The key bit is the multipurpose
ExecWB function. The second param controls whether the printer
selection dialog is shown or not. I generally tell it not to
prompt, which goes to the default. In this example I've set it to
1 which forces a prompt.


import os, sys
import codecs
import glob
import tempfile
import time

import pygments
from pygments.lexers import get_lexer_for_filename
from pygments.formatters import HtmlFormatter
import win32com.client


css_filepath = os.path.join (os.path.dirname (__file__), "print.css")

def main (fileglob, encoding="utf-8"):
  ie = win32com.client.gencache.EnsureDispatch 
("InternetExplorer.Application")

  html_filepaths = []
  try:
for filepath in glob.glob (fileglob):
  formatter = HtmlFormatter (
title=filepath,
linenos="inline",
full=True,
cssfile=css_filepath,
noclobber_cssfile=True
  )
  lexer = get_lexer_for_filename (filepath)
  with tempfile.NamedTemporaryFile (suffix=".html", delete=False) 
as html_file:

utext = codecs.open (filepath, encoding=encoding).read ()
highlighted = pygments.highlight (utext, lexer, formatter)
html_file.write (highlighted.encode ("utf8"))

  #
  # Load the temporary HTML file up in IE and
  # print it to the default printer, relying
  # on the fact the IE will load Windows filepaths
  # without strictly requiring file:// URLs with
  # escaped paths.
  #
  ie.Navigate (html_file.name)
  while ie.ReadyState != 4 or ie.Busy:
pass
  ie.ExecWB (6, 1, None, None)
  while ie.ReadyState != 4 or ie.Busy:
pass
  html_filepaths.append (html_file.name)
  finally:
#
# This is arbitrary, but avoids having to implement
# event handlers. It takes a while for the print
# handler to complete; wait until it does before
# closing IE.
#
time.sleep (5)
ie.Quit ()
for filepath in html_filepaths:
  os.unlink (filepath)

if __name__ == '__main__':
  main (*sys.argv[1:])





TJG
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Windows printing

2010-09-23 Thread Rance Hall
On Thu, Sep 23, 2010 at 3:40 AM, Tim Golden  wrote:
> On 23/09/2010 07:30, Rance Hall wrote:
>>

>>
>> Tim's how-to is likely not for my version of python (mine is 3.1)
>> since some of his command fail on my system because mine wants options
>> or parameters that Tim doesn't mention.
>
> I've fixed one issue: the win32print example now passes bytes for Py3.x
> and str for 2.x; that example now works for me. I haven't worked through
> the other examples yet but thanks for the heads-up.
>

Thanks for the rapid turn around on this one.



>
> OK. Thanks for the fairly clear explanation of the situation. I agree
> that a ShellExecute variant which allowed printer selection would be
> good, but I don't believe there is one. That's basically because
> ShellExecute is really what the user indirectly actions when they
> double-click or right-click on a file and choose one of the actions:
> there's no scope for additional info within the ShellExecute mechanism.
> Obviously a program called in this way is free to do whatever it wishes
> in the way of selection dialogs and the like.
>
> One thing which isn't entirely clear to me is whether your ticket-saved-
> as-a-temp-file is printer-ready, eg plain text, PS or PCL, or whether
> you'd really want to format it further before printing. On the basis
> that it's ready to go direct, the following very slight variation should
> do what I think you want: (tested only on XP; I'll try to get hold of
> a W7 machine to double-check)
>

For the first roll-out and testing I figured plaintext was good enough.

Future revisions will probably use the PDF library you also referred
to on your page.

Either way that is as printer ready as I expect I will be able to get it.

> 
> import os, sys
> import win32print
>
> printer_info = win32print.EnumPrinters (
>  win32print.PRINTER_ENUM_LOCAL | win32print.PRINTER_ENUM_CONNECTIONS
> )
> printer_names = [name for (flags, description, name, comment) in
> printer_info]
> for i, name in enumerate (printer_names):
>  print ("%d) %s" % (i + 1, name))
>
> n_printer = int (input ("Which printer: "))
> printer_name = printer_names[n_printer+1]
> print ("Using", printer_name)
>
> hPrinter = win32print.OpenPrinter (printer_name)
> #
> # ... and so on, per the original example
> #
>
> 
>
> Is this what you're after? Or have I missed the point?
>
> TJG

This has the logic of what I want, I'll test it later today on Win7
and see if I have any issues I can't resolve, I tried some of this
from the python console and dont get any errors, so it lools
promising.



Thanks again for the rapid response.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pure function problem

2010-09-23 Thread Roelof Wobben



> Date: Thu, 23 Sep 2010 05:36:58 -0400
> Subject: Re: [Tutor] pure function problem
> From: jemejo...@gmail.com
> To: tutor@python.org
> CC: rwob...@hotmail.com
> 
> The problem is that your class definition doesn't do anything to
> explicitly set those attributes.
> 
> On Thu, Sep 23, 2010 at 4:58 AM, Roelof Wobben  wrote:
> 
> > class tijd :
> >pass
> 
> You're not doing any explicit setting of attributes at the class level.
> 
> 
> > time = tijd()
> > time.hour = 20
> > time.minutes = 20
> > time.seconds = 20
> 
> You set them on this instance.
> 
> > seconds = 20
> > uitkomst = tijd()
> 
> But not on this one.
> 
> What you probably want to do is something like this:
> 
> class tijd(object):
> def __init__(self):
> self.hour = 20
> self.minutes = 20
> self.seconds = 20
> 
> Or if you prefer to set these when you create the instance, you can
> pass in values like this:
> 
> class tijd(object):
> def __init__(self, hour=20, minutes=20, seconds=20):
> self.hour = hour
> self.minutes = minutes
> self.seconds = seconds
> 
> I noticed something odd just a sec ago.  You have this:
> > uitkomst = tijd()
> > uitkomst = increment(time, seconds)
> > print uitkomst.minutes, uitkomst.seconds
> 
> You're creating a tijd instance, binding uitkomst to it, then
> overwriting that instance with what you return from increment().
> 
> Anyway, hth.
> 
> - jmj


Correct, 

I try to find a way to solve this error message.

Roelof

  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pure function problem

2010-09-23 Thread Jeremy Jones
The problem is that your class definition doesn't do anything to
explicitly set those attributes.

On Thu, Sep 23, 2010 at 4:58 AM, Roelof Wobben  wrote:

> class tijd :
>    pass

You're not doing any explicit setting of attributes at the class level.


> time = tijd()
> time.hour = 20
> time.minutes = 20
> time.seconds = 20

You set them on this instance.

> seconds = 20
> uitkomst = tijd()

But not on this one.

What you probably want to do is something like this:

class tijd(object):
def __init__(self):
self.hour = 20
self.minutes = 20
self.seconds = 20

Or if you prefer to set these when you create the instance, you can
pass in values like this:

class tijd(object):
def __init__(self, hour=20, minutes=20, seconds=20):
self.hour = hour
self.minutes = minutes
self.seconds = seconds

I noticed something odd just a sec ago.  You have this:
> uitkomst = tijd()
> uitkomst = increment(time, seconds)
> print uitkomst.minutes, uitkomst.seconds

You're creating a tijd instance, binding uitkomst to it, then
overwriting that instance with what you return from increment().

Anyway, hth.

- jmj
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] pure function problem

2010-09-23 Thread Roelof Wobben


Hello, 
 
I have to rewrite a function to a pure function.
So i have this :
 

class tijd :
pass
def increment(time, seconds):
sum = tijd()
sum.seconds = time.seconds + seconds 

if sum.seconds> 60 :
minutes, seconds = divmod(sum.seconds, 60)
sum.seconds = seconds 
sum.minutes = time.minutes + minutes
return sum
time = tijd()
time.hour = 20 
time.minutes = 20
time.seconds = 20 
seconds = 20
uitkomst = tijd()
uitkomst = increment(time, seconds)
print uitkomst.minutes, uitkomst.seconds
 
But now I get this error message :
 
Traceback (most recent call last):
  File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 22, in 
print uitkomst.minutes, uitkomst.seconds
AttributeError: tijd instance has no attribute 'minutes'
 
So it looks like uitkomst has no attribute minutes but uitkomst is a instance 
of tijd which has a attribute minutes.
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Windows printing

2010-09-23 Thread Tim Golden

On 23/09/2010 07:30, Rance Hall wrote:

I'm using this page as a reference:
http://timgolden.me.uk/python/win32_how_do_i/print.html

I'm able to print to the default printer ok, but I can't seem to find
out how to get to pick the printer I want to use.

This is from a CLI app, so there is no gui.

win32print seems like it has everything I need, I just can't quite see
how to put it together

I'd like to have my python app ask which printer to use as opposed to
just using the default printer.

win32print.EnumPrinters() does give me a list, but its not just a list
of names. the list also includes other items like network paths
depending on the level of detail you specify in EnumPrinters.


Tim has two possible ways to print.  Tim shows how to use the win32api
to pass a ShellExecute command that prints.  The catch to this command
is you have to print a file type and it has to be the default type for
an app to open.

He also shows a way to skip the ShellExecute and use the print api
directly to gain some more control.

Based on my needs, I'm pretty sure that I'll need to use win32print,


Tim's how-to is likely not for my version of python (mine is 3.1)
since some of his command fail on my system because mine wants options
or parameters that Tim doesn't mention.


I've fixed one issue: the win32print example now passes bytes for Py3.x
and str for 2.x; that example now works for me. I haven't worked through
the other examples yet but thanks for the heads-up.


I'm going to be printing automatically generated check-in tickets.

I can make the ticket, save it as a temp file, but I can not print to
the default printer, I must be able to select the destination printer.

My plan is to ask the user what printer to use for the session, and
save that printer name in a variable and direct all automated prints
to that printer.

As we move the laptop from place to place the default printer is not
always available.  And the available printer changes depending on
location.

Ideally there would be a variation of the ShellExecute command that
would let me specify a printer name.

Windows 7 is the predominate windows platform we are using.


OK. Thanks for the fairly clear explanation of the situation. I agree
that a ShellExecute variant which allowed printer selection would be
good, but I don't believe there is one. That's basically because
ShellExecute is really what the user indirectly actions when they
double-click or right-click on a file and choose one of the actions:
there's no scope for additional info within the ShellExecute mechanism.
Obviously a program called in this way is free to do whatever it wishes
in the way of selection dialogs and the like.

One thing which isn't entirely clear to me is whether your ticket-saved-
as-a-temp-file is printer-ready, eg plain text, PS or PCL, or whether
you'd really want to format it further before printing. On the basis
that it's ready to go direct, the following very slight variation should
do what I think you want: (tested only on XP; I'll try to get hold of
a W7 machine to double-check)


import os, sys
import win32print

printer_info = win32print.EnumPrinters (
  win32print.PRINTER_ENUM_LOCAL | win32print.PRINTER_ENUM_CONNECTIONS
)
printer_names = [name for (flags, description, name, comment) in 
printer_info]

for i, name in enumerate (printer_names):
  print ("%d) %s" % (i + 1, name))

n_printer = int (input ("Which printer: "))
printer_name = printer_names[n_printer+1]
print ("Using", printer_name)

hPrinter = win32print.OpenPrinter (printer_name)
#
# ... and so on, per the original example
#



Is this what you're after? Or have I missed the point?

TJG
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help-Embedding Python in C#

2010-09-23 Thread Steven D'Aprano
On Thu, 23 Sep 2010 03:17:39 pm ranjan das wrote:

> What I want to do is write my code completely in Python (as gainst
> iron python), 

Iron Python *is* Python. It's just a different implementation, with 
built-in support for Dot-Net.


> copy it to the visual studio editor and create a web 
> based application (I want it to be interactive) as against building
> an exe file which would mean params would have to be hard coded.


How does building an exe file mean that params would have to be hard 
coded? What sort of params?

And how does this description match what you asked earlier:

"I need to run/execute python module in C#.  I am using python 2.6 and 
visual studio 10"


So, which do you want to do: run Python code in a browser, or run it 
is C#?


> Objective: Write the code completely in python and then from it
> create a windows web based application.

If it's web-based, why does it have to be Windows-only?




-- 
Steven D'Aprano 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor