Re: [Tutor] web-based python?

2010-08-02 Thread Carlos Guerrero
IMHO, i believe that yes you can run django inside that server, but in a
different way,

this is how i believe this could be possible: do your django app but do it
inside the django source folder you can download from the official site, and
make it so, that all functions and models you need from django can be found
by the interpreter,  and make it run well in your computer without
installing django in it, but making it work as a standalone python app. Then
upload all the code to the server, and just like you would do by ssh command
line, invoking commands to run the django apps and the httpserver, invoke
the commands, -from- a .py script also in the server, so that by entering in
www.example.com/rundjangoserver.py would make the django server run.

just a thought, hope others can give more light to this,

best regards.



On Mon, Aug 2, 2010 at 11:38 PM, Che M  wrote:

>
>
> Thanks, Alan, for this set of helpful pointers.  Just a few responses.
>
>
> > Actually web apps are all pretty similar. They consist of three basic
> > parts
> > (maybe 4):
> > 1) A mechanism for mapping a URL to a Python function or method.
> > 2) A mechanism for generating HTML with embedded data values
> > 3) A data storage mechanism
> > 4) Some client code for a more dynamic feel
>
> What does "client code" and "more dynamic feel" mean here?
>
>
> > > - The easiest possible "Hello, World!" (just text) in a web browser.
> >
> > Hello, World!
> >
> > That's it as a one liner.
>
> I guess I meant the easiest possible "Hello, World!" that incorporates
> Python and works through a server, etc.  This is just the HTML.  And
> even with this, a total beginner will have no idea that he or she should
> copy that into a Notepad window, save it as helloworld.html, and then
> open that file from Firefox to see it as HTML.  The point is, in many
> discussions of web programming all the elements (and there are
> many) are scattered and disconnected from the concrete steps one
> needs to take to put them into working order.
>
> I recall that CherryPy has a little walk-through on how to get something
> very simple working with it, and that's closer to what I'm recommending.
> (Though obviously you're just answering bullet points in an email and
> this is not your tutorial :D ).
>
>
> > If you want it as a CGI program in Python its only slightly longer
> > and the CGI documentation shows you how...
>
> Probably that's what I'm after, but my guess is the CGI documentation
> is not particularly approachable (though haven't checked).  A beginner
> would also not know where "the" CGI documentation is.
>
>
> > > - How you can get more than just text on a web app, that is,
> > > widgets, and
> > > therefore what are currently the options for that (learning
> > > javascript and whatever
> > > widget toolkits are out there for that; qooxdoo; Pyjamas; others).
> >
> > This is where it gets very complicated.
>
> And yet I think this what it's all about.  When beginners think about
> a web app (or dynamic web page as someone else here put it), they
> don't think about HTML and text going back and forth to/from a server,
> they think about widgets similar to widgets seen on the desktop
> (calendars, buttons, textboxes, checkboxes, etc.).  I was excited to
> see the Quooxdoo widget set and heard it might be possible to use
> it with a Python backend...via JSON (which I don't know about) but
> it was too nebulous to motivate pursuing when I am still working on
> learning desktop programming.
>
>
> > > - How you can develop your web app on your own computer and when you
> > > need to test it actually on the web.
> >
> > Thats usually just a case of running a web server on your PC.
>
> And that's its own topic.  "Running a web server on your PC" rings zero
> bells for beginners.
>
> > Wikipedia is your friend and the partial topic that I did on web
> > programming did include some of the basic stuff with lots of
> > links to Wikipedia articles.
>
> I don't think Wikipedia is the beginner's friend on this sort of thing.
> I have not found it good for learning how to program.  Just looking
> at the topic "web development" shows this; it is an overview of the
> field, but there is no instructional/tutorial material.  It doesn't teach
> how to do it.
>
> > HTH,
>
> It is helpful, and like anything one can probably work his or her way
> through
> the topic slowly and stumblingly, but I do think that a thorough
> starting-with-
> zero-knowledge-and-defining-all-terms tutorial would be a wonderful thing
> to
> have.  As you said before, web programming is a lot more involved than
> desktop programming.  I think it would be really a fun challenge to put
> together a great soup-to-nuts tutorial on this (but I am far from the one
> to do it!), since it incorporates so many elements.  I wish you luck on
> the Py3 tutorial and and web app tutorial work when you have the chance.
>
> Thanks,
> Che
>
>
> ___
> Tutor maillist  -  Tutor@

Re: [Tutor] How to get script to detect whether a file exists?

2010-08-02 Thread David Hutto
On Tue, Aug 3, 2010 at 12:05 AM, David Hutto  wrote:
> On Mon, Aug 2, 2010 at 8:53 PM, Richard D. Moores  wrote:
>> On Mon, Aug 2, 2010 at 16:57, Steven D'Aprano  wrote:
>>>  # File *probably* doesn't exist. Consider better error checking.
>>
>> Steve, before I dig into your detailed reply, please tell me what you
>> meant by " # File *probably* doesn't exist. Consider better error
>> checking.".
>
>
> He was referring to the uncertainty principle that applies to all man
> and life, ain't that right stephan?...*wink*, *wink*, *nudge*,
> *nudge*.
>>
>> Context was
>>
>> def load(path):
>>   """Open file given by path if it exists, and return its contents.
>>   If it doesn't exist, save and return the default contents.
>>   """
>>   try:
>>       f = open(path, 'r')
>>   except IOError:
>>       # File *probably* doesn't exist. Consider better error checking.
>>       data = []
>>       save(path, data)
>>   else:
>>       data = pickle.load(f)
>>       f.close()
>>   return data
>>
>> Dick
>> ___
>> Tutor maillist  -  tu...@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>

I know that sometimes, in the darkof night, i say  stephan of oracle
eternance, please impart to me thy wisdom. And stephan answers with
bowels in hand, and relevance upon his tongue he delivers our saving
grace.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] web-based python?

2010-08-02 Thread Che M



Thanks, Alan, for this set of helpful pointers.  Just a few responses.

> Actually web apps are all pretty similar. They consist of three basic 
> parts
> (maybe 4):
> 1) A mechanism for mapping a URL to a Python function or method.
> 2) A mechanism for generating HTML with embedded data values
> 3) A data storage mechanism
> 4) Some client code for a more dynamic feel

What does "client code" and "more dynamic feel" mean here?

> > - The easiest possible "Hello, World!" (just text) in a web browser.
> 
> Hello, World!
> 
> That's it as a one liner.

I guess I meant the easiest possible "Hello, World!" that incorporates
Python and works through a server, etc.  This is just the HTML.  And
even with this, a total beginner will have no idea that he or she should
copy that into a Notepad window, save it as helloworld.html, and then
open that file from Firefox to see it as HTML.  The point is, in many
discussions of web programming all the elements (and there are 
many) are scattered and disconnected from the concrete steps one 
needs to take to put them into working order.  

I recall that CherryPy has a little walk-through on how to get something
very simple working with it, and that's closer to what I'm recommending.
(Though obviously you're just answering bullet points in an email and
this is not your tutorial :D ).

> If you want it as a CGI program in Python its only slightly longer
> and the CGI documentation shows you how...

Probably that's what I'm after, but my guess is the CGI documentation
is not particularly approachable (though haven't checked).  A beginner
would also not know where "the" CGI documentation is.

> > - How you can get more than just text on a web app, that is, 
> > widgets, and
> >   therefore what are currently the options for that (learning 
> > javascript and whatever
> >   widget toolkits are out there for that; qooxdoo; Pyjamas; others).
> 
> This is where it gets very complicated. 

And yet I think this what it's all about.  When beginners think about
a web app (or dynamic web page as someone else here put it), they
don't think about HTML and text going back and forth to/from a server, 
they think about widgets similar to widgets seen on the desktop 
(calendars, buttons, textboxes, checkboxes, etc.).  I was excited to
see the Quooxdoo widget set and heard it might be possible to use
it with a Python backend...via JSON (which I don't know about) but
it was too nebulous to motivate pursuing when I am still working on
learning desktop programming.

> > - How you can develop your web app on your own computer and when you
> >   need to test it actually on the web.
> 
> Thats usually just a case of running a web server on your PC.

And that's its own topic.  "Running a web server on your PC" rings zero
bells for beginners.  

> Wikipedia is your friend and the partial topic that I did on web
> programming did include some of the basic stuff with lots of
> links to Wikipedia articles.

I don't think Wikipedia is the beginner's friend on this sort of thing.
I have not found it good for learning how to program.  Just looking
at the topic "web development" shows this; it is an overview of the
field, but there is no instructional/tutorial material.  It doesn't teach
how to do it.

> HTH,

It is helpful, and like anything one can probably work his or her way through
the topic slowly and stumblingly, but I do think that a thorough starting-with-
zero-knowledge-and-defining-all-terms tutorial would be a wonderful thing to 
have.  As you said before, web programming is a lot more involved than 
desktop programming.  I think it would be really a fun challenge to put
together a great soup-to-nuts tutorial on this (but I am far from the one
to do it!), since it incorporates so many elements.  I wish you luck on
the Py3 tutorial and and web app tutorial work when you have the chance.

Thanks,
Che

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


Re: [Tutor] How to get script to detect whether a file exists?

2010-08-02 Thread David Hutto
On Mon, Aug 2, 2010 at 8:53 PM, Richard D. Moores  wrote:
> On Mon, Aug 2, 2010 at 16:57, Steven D'Aprano  wrote:
>>  # File *probably* doesn't exist. Consider better error checking.
>
> Steve, before I dig into your detailed reply, please tell me what you
> meant by " # File *probably* doesn't exist. Consider better error
> checking.".


He was referring to the uncertainty principle that applies to all man
and life, ain't that right stephan?...*wink*, *wink*, *nudge*,
*nudge*.
>
> Context was
>
> def load(path):
>   """Open file given by path if it exists, and return its contents.
>   If it doesn't exist, save and return the default contents.
>   """
>   try:
>       f = open(path, 'r')
>   except IOError:
>       # File *probably* doesn't exist. Consider better error checking.
>       data = []
>       save(path, data)
>   else:
>       data = pickle.load(f)
>       f.close()
>   return data
>
> Dick
> ___
> Tutor maillist  -  tu...@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] How to get script to detect whether a file exists?

2010-08-02 Thread Richard D. Moores
On Mon, Aug 2, 2010 at 16:57, Steven D'Aprano  wrote:
>  # File *probably* doesn't exist. Consider better error checking.

Steve, before I dig into your detailed reply, please tell me what you
meant by " # File *probably* doesn't exist. Consider better error
checking.".

Context was

def load(path):
  """Open file given by path if it exists, and return its contents.
  If it doesn't exist, save and return the default contents.
  """
  try:
      f = open(path, 'r')
  except IOError:
      # File *probably* doesn't exist. Consider better error checking.
      data = []
      save(path, data)
  else:
      data = pickle.load(f)
      f.close()
  return data

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


Re: [Tutor] How to get script to detect whether a file exists?

2010-08-02 Thread Richard D. Moores
On Mon, Aug 2, 2010 at 16:55, Alan Gauld  wrote:
> "Richard D. Moores"  wrote
>
>> By golly, you're right! Your point led to changes in 4 lines, the ones
>> highlighted: 
>
> Its a Good Thing(TM) to keep your interface specs consistent so
> I'd change the order of the parameters in repickling() to match
> those in create_pickle_file()

Yes, I discovered that. A good lesson. That was one factor that kept
me from recognizing that create_pickle_file() and repickling() were
essentially identical, and as Hugo pointed out, one could be removed.
I did that. See 

>
> For bonus points create a PickleFile class that has dump(),
> load() and repickle() methods - and uses __init__() for create obviously.
> The class can store the file name for convenience.

Hoo boy, how much time do I have? I've yet to create a class, though
I've studied them a bit. For example in an older version of your
tutorial -- the bank account example.

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


Re: [Tutor] How to get script to detect whether a file exists?

2010-08-02 Thread Steven D'Aprano
On Tue, 3 Aug 2010 08:42:01 am Richard D. Moores wrote:
> On Mon, Aug 2, 2010 at 14:28, Hugo Arts  wrote:
> > On Mon, Aug 2, 2010 at 8:58 PM, Richard D. Moores 
 wrote:
> >> OK, here's my attempt: .
> >>  Better?
> >
> > Much better. But why is that F in the argument list of both
> > functions? It's overwritten immediately with the open() call, so it
> > seems unnecessary to include in the arguments.
>
> I need it for lines 36 and 37, don't I?
>
> Here's the latest incarnation:
> 


One hint is that functions that do similar things should have similar 
signatures. (The signature of a function is the list of arguments it 
takes.) So create_pickle_file and repickling do similar things, they 
should look similar. The F argument isn't used, it's just immediately 
thrown away and replaced, so drop it:

def create_pickle_file(path, D):
F = open(path, 'wb')
pickle.dump(D, F)
F.close()
 
def repickling(path, D):
F = open(path, 'wb')
pickle.dump(D, F)

Now, let's look carefully at the bodies of the functions. The first 
shares 2 lines out of 3 with the second. The second shares 100% of it's 
body with the first. The *only* difference is a trivial one: in the 
first function, the opened file is explicitly closed, while in the 
second function, the opened file is automatically closed.

In other words, your two functions do EXACTLY the same thing. Let's 
throw one out, and give the survivor a nicer name and some help text 
and documentation (although in this case the function is so simple it 
hardly needs it):

def save(path, D):
"""Open file given by path and save D to it.

Returns nothing.
"""
F = open(path, 'wb')
pickle.dump(D, F)
F.close()

Notice that the function name says *what* it does ("save") rather than 
*how* it does it ("pickling"). You might change your mind and decide 
later that instead of pickle you want to use an INI file, or JSON, or 
XML, or something else.

Also, I prefer to explicitly close files, although on a small script 
like this it makes no real difference. Feel free to leave that line 
out.

Now how do you use it? Let's look what you do next:

try:
F_unused = open(path1, 'rb')
F_used = open(path2, 'rb')
except IOError:
unused_ints = [x for x in range(1, record_label_num_pages + 1)]
used_ints = []
create_pickle_file(path1, 'F_unused', unused_ints)
create_pickle_file(path2, 'F_used', used_ints)
print("Pickle files have been created.") 
print()

There's a few problems there. For starters, if *either* file is missing, 
BOTH get re-created. Surely that's not what you want? You only want to 
re-create the missing file. Worse, if an IOError does occur, the 
variables F_used and F_unused never get set, so when you try to used 
those variables later, you'll have a problem.

I'm not sure why you need to store both used and unused numbers. Surely 
you can calculate one from the other? So here's my thoughts...


record_label_name = "ABC_Classics"
record_label_num_pages = 37

used_ints_pickle_filename = record_label_name + "_used_ints.pkl"
path = '/p31working/Pickles/' + used_ints_pickle_filename

# These are the available page numbers.
pool = range(1, record_label_num_pages + 1)

def save(path, D):
"""Open file given by path and save D to it.

Returns nothing.
"""
F = open(path, 'wb')
pickle.dump(D, F)
F.close()

def load(path):
"""Open file given by path if it exists, and return its contents.
If it doesn't exist, save and return the default contents.
"""
try:
f = open(path, 'r')
except IOError:
# File *probably* doesn't exist. Consider better error checking.
data = []
save(path, data)
else:
data = pickle.load(f)
f.close()
return data

used_page_numbers = load(path)
unused_page_numbers = [n for n in pool if n not in used_page_numbers]
if not unused_page_numbers:
print("All pages checked.")
print("Program will now close.")
sleep(2.1)
sys.exit()


and now that you have a list of unused page numbers, continue on with 
the rest of your program.



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


Re: [Tutor] How to get script to detect whether a file exists?

2010-08-02 Thread Alan Gauld

"Richard D. Moores"  wrote

By golly, you're right! Your point led to changes in 4 lines, the 
ones

highlighted: 


Its a Good Thing(TM) to keep your interface specs consistent so
I'd change the order of the parameters in repickling() to match
those in create_pickle_file()

For bonus points create a PickleFile class that has dump(),
load() and repickle() methods - and uses __init__() for create 
obviously.

The class can store the file name for convenience.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


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


Re: [Tutor] How to get script to detect whether a file exists?

2010-08-02 Thread Richard D. Moores
On Mon, Aug 2, 2010 at 15:43, Hugo Arts  wrote:
> On Tue, Aug 3, 2010 at 12:42 AM, Richard D. Moores  wrote:
>> On Mon, Aug 2, 2010 at 14:28, Hugo Arts  wrote:
>>> On Mon, Aug 2, 2010 at 8:58 PM, Richard D. Moores  
>>> wrote:

 OK, here's my attempt: .  Better?

>>>
>>> Much better. But why is that F in the argument list of both functions?
>>> It's overwritten immediately with the open() call, so it seems
>>> unnecessary to include in the arguments.
>>
>> I need it for lines 36 and 37, don't I?
>>
>> Here's the latest incarnation: 
>>
>> Dick
>>
>
> Do you? you're just passing in the strings "F_used" and "F_unused",
> and you're not even using them inside the function. I'd say cut it all
> out.

By golly, you're right! Your point led to changes in 4 lines, the ones
highlighted: 

Thanks very much, Hugo.

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


Re: [Tutor] sys.exit help

2010-08-02 Thread Richard D. Moores
On Mon, Aug 2, 2010 at 13:48, Evert Rol  wrote:
> (replying to the full list; hope that was intended.)
>
 I was wondering how can I change sys.exit so if you use command line to 
 run the program. it prompts a message asking if the user wants to exit 
 instead of automatically just exiting?
>>>
>>> Just write a wrapper exit() function around sys.exit that does that.
>>
>> In a post 2 minutes after yours, Steven D'Aprano says, "write your own
>> quit() function that
>> asks the user and then calls sys.exit if they say yes."
>>
>> Is that an example of what you meant by a wrapper? I've never been
>> sure I understood the term, "wrapper".
>
> Yes. A "wrapper function" would be a function that "wraps itself around" 
> something else, most of the time around another function. It's often used to 
> expand original functionality of a function, or to make life easier it you 
> need to always set some variables before calling the original function.
> In Python, you could almost call it a decorator, although in this case that 
> wouldn't be a good idea. And wrapper function (as far as I'm aware) is a more 
> general term.
>
> For fun I just Googled for "wrapper function" (always useful). First hit 
> leads to wikipedia: http://en.wikipedia.org/wiki/Wrapper_function (though 
> it's a short wiki entry, and I'm not sure how much extra it would clarify).

Thanks, Evert, for your explanation. A big help.

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


Re: [Tutor] How to get script to detect whether a file exists?

2010-08-02 Thread Hugo Arts
On Tue, Aug 3, 2010 at 12:42 AM, Richard D. Moores  wrote:
> On Mon, Aug 2, 2010 at 14:28, Hugo Arts  wrote:
>> On Mon, Aug 2, 2010 at 8:58 PM, Richard D. Moores  wrote:
>>>
>>> OK, here's my attempt: .  Better?
>>>
>>
>> Much better. But why is that F in the argument list of both functions?
>> It's overwritten immediately with the open() call, so it seems
>> unnecessary to include in the arguments.
>
> I need it for lines 36 and 37, don't I?
>
> Here's the latest incarnation: 
>
> Dick
>

Do you? you're just passing in the strings "F_used" and "F_unused",
and you're not even using them inside the function. I'd say cut it all
out.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to get script to detect whether a file exists?

2010-08-02 Thread Richard D. Moores
On Mon, Aug 2, 2010 at 14:28, Hugo Arts  wrote:
> On Mon, Aug 2, 2010 at 8:58 PM, Richard D. Moores  wrote:
>>
>> OK, here's my attempt: .  Better?
>>
>
> Much better. But why is that F in the argument list of both functions?
> It's overwritten immediately with the open() call, so it seems
> unnecessary to include in the arguments.

I need it for lines 36 and 37, don't I?

Here's the latest incarnation: 

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


Re: [Tutor] How to get script to detect whether a file exists?

2010-08-02 Thread Hugo Arts
On Mon, Aug 2, 2010 at 8:58 PM, Richard D. Moores  wrote:
>
> OK, here's my attempt: .  Better?
>

Much better. But why is that F in the argument list of both functions?
It's overwritten immediately with the open() call, so it seems
unnecessary to include in the arguments.

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


Re: [Tutor] global exception handling?

2010-08-02 Thread Evert Rol
> A week or two back I asked this list about how to deal with SQLite database 
> errors like 'database is locked'.  Since then I figured out one way to 
> reproduce that error (*see p.s. below if anyone is interested).  I can also 
> then catch the error with a try/except block and prevent it from causing 
> problems.
> 
> But, the issue is, I have many places where I write to the database and would 
> have to embed each of these in a try/except block.  I can do that, but 
> wondered if there is a "global" way to catch this 'database is locked' error? 
>  I found someone asking this sort of question online but it doesn't appear to 
> be answered:
> http://bytes.com/topic/python/answers/799486-how-do-i-prevent-exceptions-stopping-execution-global-exception-handler

I'm not sure why you would like to do that: your code assumes the database 
interaction works fine, and based on that just continues it's normal flow. If 
the database is locked, you'll need to do something to prevent your code 
crashing further down, which is what you put in the except OperationalError: 
block. I would assume that the error handling depends on where you are in the 
code.
If you can always perform the same type of error handling, just create a 
convenience function (possibly with the SQL statement as argument) that calls 
the database and returns the results, and put the database call inside the try: 
except: clause. Then you need to do this only once.

A global way to catch the database-locked exception is just to put the try: 
except OperationalError: around your complete code. Exceptions propagate all 
the way to the function where your program started, and if you catch it there, 
you will catch every OperationalError exception from anywhere in the code. Of 
course, your program then always exits anyway, because you can't return to the 
point where the the exception was thrown (or maybe you can, but not that I'm 
aware of. I wouldn't recommend it though).


> Thanks,
> Che
> 
> p.s. *I use the nice program SQLite Database Browser and if I edit a field in 
> the database my Python app is accessing, click "Apply changes", but I do 
> *not* save the changes (that is, I do not click the disk icon), when I go to 
> write to that database from my Python app, I get a 'database is locked' error.

Sounds like somewhat odd behaviour to me: "apply changes" for me means "apply & 
commit", ie, it includes the save operation. Might just be me.
I guess "Apply changes" opens the database connection, but then "save" performs 
the actual commit to the database, and in the meantime the database is locked.

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


Re: [Tutor] sys.exit help

2010-08-02 Thread Evert Rol
(replying to the full list; hope that was intended.)

>>> I was wondering how can I change sys.exit so if you use command line to run 
>>> the program. it prompts a message asking if the user wants to exit instead 
>>> of automatically just exiting?
>> 
>> Just write a wrapper exit() function around sys.exit that does that.
> 
> In a post 2 minutes after yours, Steven D'Aprano says, "write your own
> quit() function that
> asks the user and then calls sys.exit if they say yes."
> 
> Is that an example of what you meant by a wrapper? I've never been
> sure I understood the term, "wrapper".

Yes. A "wrapper function" would be a function that "wraps itself around" 
something else, most of the time around another function. It's often used to 
expand original functionality of a function, or to make life easier it you need 
to always set some variables before calling the original function.
In Python, you could almost call it a decorator, although in this case that 
wouldn't be a good idea. And wrapper function (as far as I'm aware) is a more 
general term.

For fun I just Googled for "wrapper function" (always useful). First hit leads 
to wikipedia: http://en.wikipedia.org/wiki/Wrapper_function (though it's a 
short wiki entry, and I'm not sure how much extra it would clarify).

  Evert

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


[Tutor] global exception handling?

2010-08-02 Thread Che M

A week or two back I asked this list about how to deal with SQLite database 
errors like 'database is locked'.  Since then I figured out one way to 
reproduce that error (*see p.s. below if anyone is interested).  I can also 
then catch the error with a try/except block and prevent it from causing 
problems.

But, the issue is, I have many places where I write to the database and would 
have to embed each of these in a try/except block.  I can do that, but wondered 
if there is a "global" way to catch this 'database is locked' error?  I found 
someone asking this sort of question online but it doesn't appear to be 
answered:
http://bytes.com/topic/python/answers/799486-how-do-i-prevent-exceptions-stopping-execution-global-exception-handler

Thanks,
Che

p.s. *I use the nice program SQLite Database Browser and if I edit a field in
 the database my Python app is accessing, click "Apply changes", but I do *not* 
save the changes (that is, I do not click the disk icon), when I go to write
 to that database from my Python app, I get a 'database is locked' error.

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


Re: [Tutor] How to get script to detect whether a file exists?

2010-08-02 Thread Richard D. Moores
On Sun, Aug 1, 2010 at 17:38, Hugo Arts  wrote:
> On Mon, Aug 2, 2010 at 2:26 AM, Richard D. Moores  wrote:
>>
>> Well, I'd like to try. Could you give me, say, an outline of what
>> might be a good way? Actually, before I changed to the error catching,
>> I tried to break it up into a bunch of small functions. But they got
>> all tangled up with some functions returning the calling of others,
>> that I couldn't get them straightened out. Also, some were required to
>> have such a long string of arguments I couldn't get them all on one
>> line.
>>
>
> For starters, the code recreating both your files is almost exactly
> the same, so you can easily turn that into one function and call it
> twice. I see two necessary arguments, the path and the data you're
> dumping in. See if you can work that one out.
>
> The file saving code at the end is another one that can be easily made
> into one function and called twice. If you get those two pieces done
> you should be in good shape.

OK, here's my attempt: .  Better?

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


Re: [Tutor] Where to start with Unit Testing

2010-08-02 Thread Che M

 
> Che, from the analogies you made, it looks like you might not have very
> clear what Unit Testing is for.
> 
> True, UT is a way to automate tests that otherwise you should do
> manually (as per your analogy), but the test you automate with UT are
> not a "one off" thing (as it is processing the data needed to publish a
> paper): depending on the coding philosophy you follow, you might run UT
> as often as every couple of hours of coding (as it is in certain agile
> programming techniques).
> 
> UT is there to give you a tool to prevent regression *when/if you modify
> or refactor your code* (which is the norm if you are a professional
> programmer), and its advantages grow exponentially with the increase of
> complexity of the code and the increase of number of developers working
> on the project (it is very easy to break someone's else code... there is
> a reason for which "blame" - http://blame.sourceforge.net/ - is called
> that way!).
> 
> If you are an hobbyist programmer busy on a simple one-off small app,
> you may skip UT altogether, manually inspect the behaviour of your
> program, and never regret it. 
> 
> But if you are writing an e-commerce application that will organise
> transaction for millions of euros of revenue monthly, UT is probably the
> very first code you will want to commit to your repo.

Mac, I found this an excellent brief overview of UT and your points all
seem very strong to me.  Thanks very much.  I admit I didn't really know
anything about the topic and was mentioning my feelings on the matter
partly to elicit enlightening responses like this (maybe because I was feeling 
like I was being irresponsible with my own project by not learning UT 
and running tests).  

I am in the "hobbyist programmer busy on a simple one-off small app"
camp ("simple" is relative...though it is clearly nothing like a big 
e-commerce application!), so I feel OK with foregoing getting into UT 
for now.  If things get more complex and I at some point have actual users
instead of the large number of vapor users I have now (:D) I may buckle
down and learn it.

> PS: I did not comment on the analogy with evolution, because did not get
> the parallelism you were trying to draw. Care to explain?

I just meant that evolution by natural selection works on a "good enough"
principle:  that successful species evolve not toward the most perfected
forms but the forms that are simply good enough to allow them to pass
on enough of their genes to stay in the game.  And sometimes "good
enough" is good enough--that is, you shouldn't waste your time doing
things perfectly properly. In my case, I thought doing things perfectly 
properly would be learning all about UT and bringing that into my 
development process--but manual inspection would be "good enough".
(But now I see that really it *is* proper to skip UT if the project doesn't 
warrant it).

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


Re: [Tutor] Where to start with Unit Testing

2010-08-02 Thread Huy Ton That
One final note, that I thought might be useful to others.

I've just discovered doctest, which allows you to run tests on your embedded
function/class documentation.

Check it out here:
http://docs.python.org/tutorial/stdlib.html#quality-control

On Sun, Aug 1, 2010 at 3:30 AM, Huy Ton That  wrote:

> Hi all,
>
> Do any of you have any feedback, strategies and best practices related to
> unit testing within Python. This is a relatively new topic for me. I was
> thinking of starting with reading the documentation associate with the
> unittest module.
>
> -Huy
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Where to start with Unit Testing

2010-08-02 Thread Huy Ton That
Thanks additionally for your insight gems.

Without reading too much into it, it was quite simple to create a series of
test classes which just run some expected assertion values on a small
scenario of inputs and what's expected.

I usually find that I learn best by dabbling around in source code, then
writing some code to test what I think I know.

I'll try to integrate this and commit this to memory with time where I won't
have to look back as much (:


On Sun, Aug 1, 2010 at 9:25 AM, Mac Ryan  wrote:

> On Sun, 2010-08-01 at 03:30 -0400, Huy Ton That wrote:
> > Hi all,
> >
> > Do any of you have any feedback, strategies and best practices related
> > to unit testing within Python. This is a relatively new topic for me.
> > I was thinking of starting with reading the documentation associate
> > with the unittest module.
>
> My answer falls in the category "feedback" (I was also going to mention
> the diveintopython page, but somebody else has done that already!), so
> you should be aware what follows is highly subjective...
>
> JUST THINK... IN PYTHON!
>   IMO, unit testing is really easy to pick up. It really does not
> amount to much more than taking note (in python) of what you are
> thinking when you are coding.
>   If you are anything like me, when you code you keep on formulating
> "rules" in your head, in the line of "when everything works as expected,
> if the methods iterates four times, then this method must return X" or
> "when everything works as expected, if a user enter a value over 212
> then the script must throw this exception", etc...
>   * the "when everything works as expected" translates in "this test
> pass when..."
>   * the "if X" translates in your test case (i.e. the scenario you are
> testing for)
>  * the "then Y" translates in "the outcome of my test case must be Y"
>
> TESTING IS VALUABLE IN THE LONG RUN
>   At times, designing and coding a test is a time-consuming activity,
> and if the code is particularly straightforward you might be tempted to
> skip the unit testing altogether. In my experience - however - unit
> testing is never as useful on the spot as it is three months from now,
> when you will have/want/choose to modify a little bit of your old code,
> and all of a sudden everything will break. In the latter scenario, your
> test suite will be an invaluable asset.
>
> FUNCTIONAL PROGRAMMING WINS
>   The most difficult thing in writing a test, is replicating the state
> of the environment needed for the test to happen. This is especially
> (but not uniquely) true for DB-driven applications, when you might wish
> to perform test on methods that interact with the DB. In that case you
> have to create a test DB, populate it with ~credible data, etc...
>   The most "functional" (as in functional programming, i.e.
> machine-state independent) is your code, the easiest is to write a test.
> Example: if you need to check a method that validate the postal code of
> an address based on the name of the city, it is easier to test a method
> that is invoked with "validate_postal_code(code, city)" rather than one
> that is invoked with "validate_postal_address(user)" and that will have
> to retrieve the full address of a user from a DB, and extract the city
> and postal address from it.
>
> MVC WINS
>   I never test UI's. I know it is bad... but it is simply too
> time-consuming for me (I'll be very glad if somebody reading this will
> show me how one can make it snappier!). This means - at least for me -
> that writing tests become extremely easier for me if I keep separated
> the presentation layer from all the rest of the stuff.
>
> EVERY BUG IS A TEST YET NOT WRITTEN
>   A program that passes all its tests is not necessarily a bug-free
> program. But once you find a new bug, try to make a point of writing a
> new test that check for that particular scenario in which said bug is
> happening.
>
> TEST-DRIVEN IS BETTER
>   What I find useful (although not always applicable) is to start my
> programming session by writing the tests before I write the code to be
> tested. This somehow reconnect to my previously articulated "just
> think... in python!" point: you are however *already doing a list of
> rules* in your head, before writing code, so you could well write it
> down directly in code. All you need is to create a mock method/function
> in your code with the same signature you are using in your test. For
> example. You could write tests in the form:
>
>assertEqual(better_square_root(9), 3)
>assertRaises(ValueError, better_square_root, -4)
>
> and then write in your module:
>
>def my_better_square_root(number):
>pass
>
> all your tests will of course initially fail, but then you will keep on
> working on the code of my_better_square_root until all your tests pass.
>
> Well, these are just my two ¢... As stated in the beginning: highly
> subjective, so keep your mind open for other (possibly opposite)
> opinions too! :)
>
> HTH,
> Mac.
>
>

Re: [Tutor] Menu not working properly

2010-08-02 Thread David Hutto
On Mon, Aug 2, 2010 at 10:41 AM, Luke Paireepinart
 wrote:
>
>
> On Aug 2, 2010, at 8:13 AM, David Hutto  wrote:
>
>> On Mon, Aug 2, 2010 at 8:00 AM, Evert Rol  wrote:
 Hello Evert Rol,
           Thank you for the menu help, I have completed it with great 
 success... There is 1 more problem I am currently having, and when I fix 
 it my program will be completed. If you are interested in helping me with 
 this last stretch, I will be greatly appreciative.

           If you respond with a yes. I will go ahead and send my code over 
 and list the problem I am currently having.
>>>
>>> Jason, it makes more sense to send this to the full tutor list, not just to 
>>> me:
>>
>> A ha haha, you hit the wrong 'reply to button'. Stupid newb says what?

The first rule of any endeavour is to learn to laugh at yourself. If
you don't have cahunas to call your own self a newb, and laugh at the
mistakes you made, after thought , then what kind of programmers will
you be?

> I hope you're kidding. If you're not, leave the list right away.

It was a joke. Bad but I laughed at it.

You are not being helpful. If you were kidding, make it more clear next time.
>>
>> there are more people who can and will help you. Unless I've missed a
>> response to a previous post of yours where people disrecommended your
>> postings, but that shouldn't happen to quickly.
> Have you heard the saying about throwing rocks at glass houses? 'cause you 
> just screwed up your reply quoting.
>
> -Luke
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Menu not working properly

2010-08-02 Thread Luke Paireepinart


On Aug 2, 2010, at 8:13 AM, David Hutto  wrote:

> On Mon, Aug 2, 2010 at 8:00 AM, Evert Rol  wrote:
>>> Hello Evert Rol,
>>>   Thank you for the menu help, I have completed it with great 
>>> success... There is 1 more problem I am currently having, and when I fix it 
>>> my program will be completed. If you are interested in helping me with this 
>>> last stretch, I will be greatly appreciative.
>>> 
>>>   If you respond with a yes. I will go ahead and send my code over 
>>> and list the problem I am currently having.
>> 
>> Jason, it makes more sense to send this to the full tutor list, not just to 
>> me:
> 
> A ha haha, you hit the wrong 'reply to button'. Stupid newb says what?
I hope you're kidding. If you're not, leave the list right away. You are not 
being helpful. If you were kidding, make it more clear next time.
> 
> there are more people who can and will help you. Unless I've missed a
> response to a previous post of yours where people disrecommended your
> postings, but that shouldn't happen to quickly.
Have you heard the saying about throwing rocks at glass houses? 'cause you just 
screwed up your reply quoting.

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


Re: [Tutor] Menu not working properly

2010-08-02 Thread David Hutto
On Mon, Aug 2, 2010 at 8:00 AM, Evert Rol  wrote:
>> Hello Evert Rol,
>>           Thank you for the menu help, I have completed it with great 
>> success... There is 1 more problem I am currently having, and when I fix it 
>> my program will be completed. If you are interested in helping me with this 
>> last stretch, I will be greatly appreciative.
>>
>>           If you respond with a yes. I will go ahead and send my code over 
>> and list the problem I am currently having.
>
> Jason, it makes more sense to send this to the full tutor list, not just to 
> me:

A ha haha, you hit the wrong 'reply to button'. Stupid newb says what?

there are more people who can and will help you. Unless I've missed a
response to a previous post of yours where people disrecommended your
postings, but that shouldn't happen to quickly.
> Although in general, it's better to try and solve the problem yourself, and 
> ask the tutor list if you're really stuck, either with an error or a concept. 
> And the 'try and solve yourself' step can take one or more days and a lot of 
> Googling, but in the end you learn a lot from it.
> So, depending on your current problem, see if you want to try yourself first, 
> or that you feel you need the input from the list.
> (Code can be included with the mail if short; use something like 
> http://python.pastebin.com/ if lengthly code.)
>
> Good luck,
>
>  Evert
>
>
>
>
>
>>
>>          -Thank You
>>
>> On Mon, Aug 2, 2010 at 3:35 AM, Evert Rol  wrote:
>> > My problem is choice 3. Exit, if you select no or put an invalid answer... 
>> > It will run menu1... but then it runs
>> >     name = raw_input ("Enter your character name. ")
>> >     print "Your character name is:", name
>> >
>> > How can i make it so it prints menu1 like normal... then asks you to enter 
>> > your selection again?
>> > instead of running the above code.
>>
>> Put it in a loop with the necessary break statements. Something like:
>>
>> while True:
>>  print menu1
>>  answer = raw_input()
>>  if ...:
>>    ...
>>    break
>>  elif ...:
>>    ...
>>  elif ...:
>>   answer = raw_input()
>>   if ...:
>>     sys.exit()
>> raw_input('character name')
>>
>> Only the first option will break out of the loop to the 'character name' 
>> question; the other two options will continue to loop, apart from the point 
>> where you exit() the whole program.
>> If you need user input until the correct input has been given, that means 
>> you'll have to wrap things in a loop (generally a while loop that you break 
>> out of when you received correct input).
>> You could factor out the actual code inside the while loop into a function, 
>> which can make the structure clearer.
>>
>>
>> Btw,
>>
>> 
>>
>> >     characterChoice = input ("Enter your choice. ")
>>
>> You have input() here, while further down raw_input(). The latter is 
>> preferred in Python 2.x. I assume this is just a minor mistake.
>>
>>
>>  Evert
>>
>>
>> >     print
>> >
>> >     if characterChoice == 1:
>> >         print """
>> >
>> > *Place Holder*
>> >
>> >         """
>> >
>> >     elif characterChoice == 2:
>> >         print "Currently under construction.\nPlease choose again."
>> >         print menu1
>> >     elif characterChoice == 3:
>> >         endProgram = raw_input ("Do you want to end program? yes or no ")
>> >         if endProgram == "yes":
>> >             sys.exit(0)
>> >         elif endProgram == "no":
>> >             print menu1
>> >         else:
>> >             print "\nInvalid Command:\nSelect from the menu again.\n"
>> >             print menu1
>> >
>> >     print
>> >     name = raw_input ("Enter your character name. ")
>> >     print "Your character name is:", name
>> > ___
>> > Tutor maillist  -  tu...@python.org
>> > To unsubscribe or change subscription options:
>> > http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
> ___
> Tutor maillist  -  tu...@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] Menu not working properly

2010-08-02 Thread Evert Rol
> Hello Evert Rol,
>   Thank you for the menu help, I have completed it with great 
> success... There is 1 more problem I am currently having, and when I fix it 
> my program will be completed. If you are interested in helping me with this 
> last stretch, I will be greatly appreciative.
> 
>   If you respond with a yes. I will go ahead and send my code over 
> and list the problem I am currently having.

Jason, it makes more sense to send this to the full tutor list, not just to me: 
there are more people who can and will help you. Unless I've missed a response 
to a previous post of yours where people disrecommended your postings, but that 
shouldn't happen to quickly.
Although in general, it's better to try and solve the problem yourself, and ask 
the tutor list if you're really stuck, either with an error or a concept. And 
the 'try and solve yourself' step can take one or more days and a lot of 
Googling, but in the end you learn a lot from it.
So, depending on your current problem, see if you want to try yourself first, 
or that you feel you need the input from the list.
(Code can be included with the mail if short; use something like 
http://python.pastebin.com/ if lengthly code.)

Good luck,

  Evert





> 
>  -Thank You
> 
> On Mon, Aug 2, 2010 at 3:35 AM, Evert Rol  wrote:
> > My problem is choice 3. Exit, if you select no or put an invalid answer... 
> > It will run menu1... but then it runs
> > name = raw_input ("Enter your character name. ")
> > print "Your character name is:", name
> >
> > How can i make it so it prints menu1 like normal... then asks you to enter 
> > your selection again?
> > instead of running the above code.
> 
> Put it in a loop with the necessary break statements. Something like:
> 
> while True:
>  print menu1
>  answer = raw_input()
>  if ...:
>...
>break
>  elif ...:
>...
>  elif ...:
>   answer = raw_input()
>   if ...:
> sys.exit()
> raw_input('character name')
> 
> Only the first option will break out of the loop to the 'character name' 
> question; the other two options will continue to loop, apart from the point 
> where you exit() the whole program.
> If you need user input until the correct input has been given, that means 
> you'll have to wrap things in a loop (generally a while loop that you break 
> out of when you received correct input).
> You could factor out the actual code inside the while loop into a function, 
> which can make the structure clearer.
> 
> 
> Btw,
> 
> 
> 
> > characterChoice = input ("Enter your choice. ")
> 
> You have input() here, while further down raw_input(). The latter is 
> preferred in Python 2.x. I assume this is just a minor mistake.
> 
> 
>  Evert
> 
> 
> > print
> >
> > if characterChoice == 1:
> > print """
> >
> > *Place Holder*
> >
> > """
> >
> > elif characterChoice == 2:
> > print "Currently under construction.\nPlease choose again."
> > print menu1
> > elif characterChoice == 3:
> > endProgram = raw_input ("Do you want to end program? yes or no ")
> > if endProgram == "yes":
> > sys.exit(0)
> > elif endProgram == "no":
> > print menu1
> > else:
> > print "\nInvalid Command:\nSelect from the menu again.\n"
> > print menu1
> >
> > print
> > name = raw_input ("Enter your character name. ")
> > print "Your character name is:", name
> > ___
> > 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] Menu not working properly

2010-08-02 Thread Evert Rol
> My problem is choice 3. Exit, if you select no or put an invalid answer... It 
> will run menu1... but then it runs
> name = raw_input ("Enter your character name. ")
> print "Your character name is:", name
> 
> How can i make it so it prints menu1 like normal... then asks you to enter 
> your selection again?
> instead of running the above code.

Put it in a loop with the necessary break statements. Something like:

while True:
  print menu1
  answer = raw_input()
  if ...:
...
break
  elif ...: 
...
  elif ...:
   answer = raw_input()
   if ...:
 sys.exit()
raw_input('character name')

Only the first option will break out of the loop to the 'character name' 
question; the other two options will continue to loop, apart from the point 
where you exit() the whole program.
If you need user input until the correct input has been given, that means 
you'll have to wrap things in a loop (generally a while loop that you break out 
of when you received correct input). 
You could factor out the actual code inside the while loop into a function, 
which can make the structure clearer.


Btw, 



> characterChoice = input ("Enter your choice. ")

You have input() here, while further down raw_input(). The latter is preferred 
in Python 2.x. I assume this is just a minor mistake.


  Evert


> print
> 
> if characterChoice == 1:
> print """
> 
> *Place Holder*
>   
> """
> 
> elif characterChoice == 2:
> print "Currently under construction.\nPlease choose again."
> print menu1
> elif characterChoice == 3:
> endProgram = raw_input ("Do you want to end program? yes or no ")
> if endProgram == "yes":
> sys.exit(0)
> elif endProgram == "no":
> print menu1
> else:
> print "\nInvalid Command:\nSelect from the menu again.\n"
> print menu1
> 
> print
> name = raw_input ("Enter your character name. ")
> print "Your character name is:", name
> ___
> 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


[Tutor] Menu not working properly

2010-08-02 Thread Jason MacFiggen
My problem is choice 3. Exit, if you select no or put an invalid answer...
It will run menu1... but then it runs
name = raw_input ("Enter your character name. ")
print "Your character name is:", name

How can i make it so it prints menu1 like normal... then asks you to enter
your selection again?
instead of running the above code.

-Thank you

import sys

def menu():
menu1 = """
Pick A Class From The Menu or choose Exit.
1. Warrior
2. Mage
3. Exit
"""
print "Welcome to Iris's Last Breath"
print menu1
characterChoice = input ("Enter your choice. ")
print

if characterChoice == 1:
print """

*Place Holder*

"""

elif characterChoice == 2:
print "Currently under construction.\nPlease choose again."
print menu1
elif characterChoice == 3:
endProgram = raw_input ("Do you want to end program? yes or no ")
if endProgram == "yes":
sys.exit(0)
elif endProgram == "no":
print menu1
else:
print "\nInvalid Command:\nSelect from the menu again.\n"
print menu1

print
name = raw_input ("Enter your character name. ")
print "Your character name is:", name
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor