Re: [Tutor] Code evaluation inside of string fails with __get_item

2010-12-11 Thread Peter Otten
Tim Johnson wrote:

> This is a resend. I note that the original had an incorrect
> `reply-to' ID attached to it. (sorry)
> --
> I'm using Python 2.6.5.
> The following problem is coming from inside of a complex code base
> and involves an implementation that I have used for years, and is
> now failing to execute in certain conditions.
> This problem occurs with either of the follow two classes, which are
> 'lifted' from 'Python Cookbook'. Class code follows:
> class Eval:

> def __getitem__(self, key):

> Under certain circumstances, the embedded is code *not* executed.

The first step is to concentrate on just one class, at one point in the 
code. Then try to control the input to the method and find an argument where 
the code reproducibly fails.

> By inserting debugging stubs, I can see that the the Eval/Evalx
> instantiation does occur, but the overloaded function call to __get_item
> does *not* occur. I have also found that a seemingly unrelated event
> having to do with file I/O must be causing a side effect. However, to keep
> things simple, I am first asking the following question:
> What would cause __get_item__ not to be called? I can confirm by

Nothing, provided 

(1) the method is spelt __getitem__ (two leading and two trailing 
underscores)

(2) the left side is a python string with legal "%(...)s"-style format 
expressions. Given a format string

s = "%(s.upper())s" 

try to feed it a real dict

print s % {"s.upper()":"OK") # should print OK

to verify that that precondition is met.

Peter

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


Re: [Tutor] using a networked data file

2010-12-11 Thread David Hutto
On Fri, Dec 10, 2010 at 10:23 PM, Bill Allen  wrote:
> This is somewhat non-Python specific   I have an idea for a Python
> application that I want to write at work.  The application needs to have a
> data file be available to multiple users for access, read and write.   I
> know that a typical database, such as mysql, would work ok.   However, I am
> trying to keep managed infrastructure down to a minimum so I am considering
> using sqlite instead.   Since there is not a database service running to
> handle requests to the sqlite database, how can I allow for multiple people
> trying to use this database at the same time?  Is this practical?

No expert, but is it a single db file per user on a server, or a
single db file that adds a table for every user?


>
> Thanks,
> Bill Allen
>
>
> ___
> 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


[Tutor] Ressources for licensing

2010-12-11 Thread Knacktus

Hi everyone,

can anybody recommend a lib or some other ressources about license 
mechanisms of desktop applications written in python. I'm thinking of a 
license-key that can be used to limit the time the application can be 
used. I also need to exploit the usage of a license server.


Cheers,

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


[Tutor] Slicing Tuples

2010-12-11 Thread John Russell
Last night I started working through a book (Beginning Python: Using Python
2.6 and Python 3.1)  I bought to learn Python, and there is an example in it
that doesn't make sense to me.

There is an example on slicing sequences that goes like this:

slice_me=("The", "next", "time", "we","meet","the","drinks","are","on","me")
sliced_tuple=slice_me[5:9]
print(sliced_tuple)

which, results in

('drinks', 'are', 'on', 'me')

there is an example a little further below that shows the same concept, only
applying it to a string, and, the result is  four characters long, starting
at the 6th position.

Now, I understand why they start where they do, because the counting starts
at 0, so 5 is the 6th element. What I don't understand is why they end where
they do. By my count, 5 to 9 would be 5 elements, not 4. With the tuple, I
thought the result was because there wasn't enough elements left, but when I
changed 5:9 to 5:8, it returned one less result.

So, my question is this, and I realize that this is *very* basic - what is
going on with the last element? Why is it returning one less than I think it
logically should. Am I missing something here? There is not much of an
explanation in the book, but I would really like to understand what's going
on here.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Code evaluation inside of string fails with __get_item

2010-12-11 Thread Tim Johnson
* Peter Otten <__pete...@web.de> [101211 03:41]:
> (1) the method is spelt __getitem__ (two leading and two trailing 
> underscores)
> 
> (2) the left side is a python string with legal "%(...)s"-style format 
> expressions. Given a format string
> 
> s = "%(s.upper())s" 
> 
> try to feed it a real dict
> 
> print s % {"s.upper()":"OK") # should print OK
> 
> to verify that that precondition is met.
  Should be 
  print s % {"s.upper()":"OK"} ## closing brace
  I've never had the occasion to use assert() or any other
  python - shooting tools, any thoughts on that?

  I am dealing with a programmatically composed format
  string, that originates from a source (html) file
  It may be 

  1)read from the file external to the object
and the source string passed into the object at instantiation.
The composed string is then translated correctly and
the embedded is evaluated.

  2)read from the source file 'within' the object namespace.
In this case, the embedded code within the composed format
is *not* evaluated. And  I can observe the
legal "%(...)s"-style format expressions.

  3)*But* (and here is the kicker), if the composed format
string is then dumped to a pickle file and then loaded
from that pickle file it is then evaluated. 

  :) As near as I can see. And that suggests a workaround.
  Unfortunately, no error messages are generated either at
  runtime or by pychecker.

  Thanks Peter
-- 
Tim 
tim at johnsons-web.com or akwebsoft.com
http://www.akwebsoft.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] role playing game - help needed

2010-12-11 Thread Lie Ryan
On 12/07/10 23:37, Robert Sjöblom wrote:
> I've been told to use input() if I know that I'll only get integers,
> and raw_input() for "everything."

That is a bad piece of advice. You should only use input() when you can
fully trust whoever doing the input (i.e. you). input() can accept any
python expressions, and this means the user can potentially execute
malicious code as well.

>>> import subprocess
>>> input("input: ")
input: subprocess.Popen(('ping', 'www.google.com'))

>>> PING www.l.google.com (66.102.11.104) 56(84) bytes of data.
64 bytes from syd01s01-in-f104.1e100.net (66.102.11.104): icmp_req=1
ttl=57 time=18.5 ms

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


Re: [Tutor] Slicing Tuples

2010-12-11 Thread Hugo Arts
On Sat, Dec 11, 2010 at 5:25 PM, John Russell  wrote:
> Last night I started working through a book (Beginning Python: Using Python
> 2.6 and Python 3.1)  I bought to learn Python, and there is an example in it
> that doesn't make sense to me.
> There is an example on slicing sequences that goes like this:
> slice_me=("The", "next", "time", "we","meet","the","drinks","are","on","me")
> sliced_tuple=slice_me[5:9]
> print(sliced_tuple)
> which, results in
> ('drinks', 'are', 'on', 'me')

That's not really what happens for me, see here:

>>> a = ("The", "next", "time", "we","meet","the","drinks","are","on","me")
>>> a[5:9]
('the', 'drinks', 'are', 'on')
>>> a[6:10]
('drinks', 'are', 'on', 'me')

[6:10] should provide the result you showed. Please make sure to
always copy-paste when quoting code, otherwise inaccuracies like this
will happen.

> there is an example a little further below that shows the same concept, only
> applying it to a string, and, the result is  four characters long, starting
> at the 6th position.
> Now, I understand why they start where they do, because the counting starts
> at 0, so 5 is the 6th element. What I don't understand is why they end where
> they do. By my count, 5 to 9 would be 5 elements, not 4. With the tuple, I
> thought the result was because there wasn't enough elements left, but when I
> changed 5:9 to 5:8, it returned one less result.
> So, my question is this, and I realize that this is *very* basic - what is
> going on with the last element? Why is it returning one less than I think it
> logically should. Am I missing something here? There is not much of an
> explanation in the book, but I would really like to understand what's going
> on here.
>

Very simple, a slice of a[5:9] will return all elements x where 5 <= x
< 9. That's actually 4 elements: 5, 6, 7, and 8. You'll notice that
while the starting number of the slice is included, the end is not.
You might think this strange, but python uses it everywhere. range
does the same:

>>> range(5, 9)
[5, 6, 7, 8]

There are some good reasons to make slices and ranges work like this.
One, you can subtract the numbers in the slice to get the length of
the slice, i.e. len(a_list[x:y]) == y - x.
Two, cutting a list up in two is now very easy and intuitive: l == l[:b] + l[b:]

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


Re: [Tutor] using a networked data file

2010-12-11 Thread Bill Allen
David,

Thanks for the feedback.   I should have been more specific on the usage of
the data.   The data will be some email addresses, names, department, and an
indicator if the email address is internal to the business or an external
contact.   So, one table with these being the fields in each record should
suffice.   The users will be presented an interface that allows them to
select one or more recipients to which a standardized email with a PDF
attachment will be sent.   All of this is no problem.   I was concerned that
with more than one user at a time potentially accessing the SQLite db at a
time would be a problem, but I see from the SQLite site and from some
discussions here on Tutor that this is perfectly fine.   The users may add
information to the db also, but since such writes will be infrequent this
too should be OK.   At least, that is the impression that I have gotten from
what I have read here and other places.   Just wanting to confirm that I
have understood this correctly.  Also, any other suggestions are welcome.

Thanks,
Bill Allen


On Sat, Dec 11, 2010 at 6:32 AM, David Hutto  wrote:

> On Fri, Dec 10, 2010 at 10:23 PM, Bill Allen  wrote:
> > This is somewhat non-Python specific   I have an idea for a Python
> > application that I want to write at work.  The application needs to have
> a
> > data file be available to multiple users for access, read and write.   I
> > know that a typical database, such as mysql, would work ok.   However, I
> am
> > trying to keep managed infrastructure down to a minimum so I am
> considering
> > using sqlite instead.   Since there is not a database service running to
> > handle requests to the sqlite database, how can I allow for multiple
> people
> > trying to use this database at the same time?  Is this practical?
>
> No expert, but is it a single db file per user on a server, or a
> single db file that adds a table for every user?
>
>
> >
> > Thanks,
> > Bill Allen
> >
> >
> > ___
> > 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] Slicing Tuples

2010-12-11 Thread Steven D'Aprano

John Russell wrote:


So, my question is this, and I realize that this is *very* basic - what is
going on with the last element? Why is it returning one less than I think it
logically should. Am I missing something here? There is not much of an
explanation in the book, but I would really like to understand what's going
on here.



If the book really doesn't explain this (as opposed to you just having 
missed it), that's a fairly serious lack!


Slicing in Python uses what is called "half-open intervals". There are 
four obvious ways to count slices:


(1) Closed interval:
both the start index and the end index are included.

(2) Open interval:
both the start index and end index are excluded.

(3) Half-open interval:
the start index is included, and the end index excluded.

(4) Half-open interval (reversed sense):
the start index is excluded, and the end index included.


Python uses #3 because it is generally the most simple and least 
error-prone. Essentially, you should consider a slice like sequence[a:b] 
to be equivalent to "take a slice of items from seq, start at index=a 
and stop when you reach b". Because you stop *at* b, b is excluded.


Indexes should be considered as falling *between* items, not on them:

0.1.2.3.4.5.6.7.8
|a|b|c|d|e|f|g|h|

Run an imaginary knife along the line marked "4", and you divide the 
sequence abcdefgh into two pieces: abcd and efgh.


Why are half-open intervals less error-prone? Because you have to adjust 
by 1 less often, and you have fewer off-by-one errors. E.g.


* Take n items starting from index i:

  Half-open: seq[i:i+n]
  Closed:seq[i:i+n-1]

* Length of a slice [i:j]:

  Half-open: j-i
  Closed:j-i+1

* Dividing a sequence into two slices with no overlap:

  Half-open:
s = seq[:i]
t = seq[i:]

  Closed:
s = seq[:i-1]
t = seq[i:]

* Splitting a string at a delimiter:
  s = "abcd:efgh"

  We want to split the string into two parts, everything before
  the colon and everything after the colon.

  Half-open:
p = s.find(':')
before = s[:p]
after = s[p+1:]

  Closed:
p = s.find(':')
before = s[:p-1]
after = s[p+1:]

* Empty slice:

  Half-open: seq[i:i] is empty
  Closed:seq[i:i] has a single item


So half-open (start included, end excluded) has many desirable 
properties. Unfortunately, it has two weaknesses:


- most people intuitively expect #1;
- when slicing in reverse, you get more off-by-one errors.

There's not much you can do about people's intuition, but since reverse 
slices are much rarer than forward slices, that's a reasonable cost to pay.




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


[Tutor] Beginning Python and other resources (was Re: Slicing Tuples)

2010-12-11 Thread David
On 12 December 2010 03:25, John Russell  wrote:
> Last night I started working through a book (Beginning Python: Using Python
> 2.6 and Python 3.1)  I bought to learn Python, and there is an example in it
> that doesn't make sense to me.

I have that book too, and several others thankfully. I'm just writing
to share my experience, in case another perspective from another
relatively new python user is helpful to anyone.

I found that book is written towards a friendly beginner level, but it
omits many details and is not a comprehensive reference. It does
include plenty of examples on many topics. I have read the opposite
criticism of other books, so it is probably impossible for one book to
fit all needs.

Personally I became weary of the food/fridge/kitchen theme of the
early examples as it did not engage my interest at all, and there is
so much of it. However I have found that book valuable for its Part
III where it covers useful applications. Although I have come to
expect that its examples will often need typos corrected or other
small modifications to get them to run properly on Python 2.6.

So while working through Parts I and II, if your experience is
anything like mine where I moved away from it fairly quickly, you will
definitely need other resources. Fortunately they are abundantly
available. In case you are unaware, a Tutorial and Reference are
integrated with Python. On my Linux box the tutorial is
file:///usr/share/doc/python-docs-x.x.x/html/tutorial/index.html and
the Alphabetic Index to the Reference is
file:///usr/share/doc/python-docs-x.x.x/html/genindex.html

I find the Tutorial easily readable, whereas the Reference can be
challenging, but it is comprehensive and likely contains the answer to
most questions, somewhere.

As an exercise I thought I'd try to find the answer to your question
using these built-in docs. The keyword is "slice" which we know from
the book. I couldn't find any coverage in the 2.6 tutorial so I looked
up "slice" in the Alphabetic Index, and the first link took me to a
section which includes the answer: "The slicing now selects all items
with index k such that i <= k < j where i and j are the specified
lower and upper bounds".

In case you are not aware, the web has a vast amount of great material
for learning Python, see for example:
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
As Python is an evolving language, one needs be mindful of the
differences between Python 2.x and Python 3.x when using this
material.

My favourite Python book of my small beginners collection is "Python 3
Object Oriented Programming" by Dusty Phillips. It claims:
"If you're new to object-oriented programming techniques, or if you
have basic Python skills, and wish to learn in depth how and when to
correctly apply object-oriented programming in Python, this is the
book for you".
I endorse that completely. Having learned the syntax basics elsewhere,
for me this is a book like no other. I find its topic coverage and all
its short examples consistently useful, powerful, and illuminating. I
find it easy to read, well matched to my level and interest, and it
has made a real difference to the code I write. I use classes with
confidence now. For example, it gave me the background and confidence
to design a custom sortable abstract class I needed, my first personal
experience of the power of OOP.

Tthe python and tutorial mailing lists are a wonderul resource as you
are obviously aware. Thanks to all the contributors from whom I
continue to learn.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Dictionaries - Using 1 Key:Value to find another

2010-12-11 Thread Al Stern
This was another execise in my book.  Following is my code for a program
that uses dictionaries to find and edit pairs of fathers and sons.  The
program works right up to the final step which is to find out if any given
father is actually a grandfather to someone else in the dictionary.  I set
up multiple generations in the dictionary so there would be available
matches.

# father son "who's your daddy" program
#create a dictionary of father son pairs.  Include multiple generations.
pairs = {"Joel" : "Al",
 "Bill" : "Joel",
 "Joseph" : "Bill",
  "Palmer" : "Bob",
 "Bob" : "Will",
 "Al" : "Royal"}
fathers = pairs.keys()
sons = pairs.values()
choice = None
while choice != "0":

print("""
Welcome to Who's Your Daddy? A mini database of fathers and sons.
When entering names, please capitilize the 1st letter of each name.

0 - Exit
1 - List all Father-Son Pairs
2 - List all Fathers
3 - Look Up Father-Son Pairs
4 - Add a Father-Son Pair
5 - Delete a Father-Son Pair
6 - Replace the Son of a Father-Son Pair
7 - Replace a Father-Son Pair
8 - Look up Grandfather_Father_Son Pairs
""")

choice = input("Choice: ")


# To end the program
if choice == "0":
print ("Thanks for playing.  Goodbye.")
# List pairs
elif choice == "1":
print ("List of all Father and Son pairs: ")
print (pairs)
elif choice == "2":
print ("List of all Fathers: ")
for fathers in pairs:
print (fathers)
elif choice == "3":
print ("Look up Father-Son pairs: ")
father = input ("What is the name of the father in the pair you want
to look up? ")
if father in pairs:
son = pairs[father]
print ("\n", father, "is the father of",son, ".")
else:
print ("\nSorry.  That father does not exist.")
elif choice == "4":
print ("Add a Father-Son pair: ")
new_father = input ("What is the name of the father you wish to add?
")
if new_father not in pairs:
new_son = input ("What is the name ofthe son you wish to add? ")
pairs[new_father] = new_son
print ("\n", new_father, "has been added.")
else:
print ("\nThat Father-Son pair already exists.  Try again.")

elif choice == "5":
print ("Delete a Father-Son pair: ")
del_father = input ("What is the name of the father in the pair you
wish to delete? ")
if del_father in pairs:
del pairs[del_father]
print ("\nThe pair in which", del_father, "is the father has
been deleted.")
else:
print ("\nSorry.", del_father, "is not a valid father name.")
elif choice == "6":
print ("Replace the son of a Father-Son Pair: ")
son_old = input ("What is the name of the father whose son you wish
to replace? ")
if son_old in pairs:
son_new = input ("What is the name of the new son in this pair?
")
pairs[son_old] = son_new
print (son_new, "has replaced", son_old, "in the list.")
else:
print ("Sorry, that son does not exist.  Try again.")
elif choice == "7":
print ("Replace a Father-Son pair: ")
father = input ("Who is the father in the Father-Son pair do you
which to replace? ")
if father in pairs:
father = input("What is the name of the father in the new
Father-Son pair? ")
son = input("What is the name of the son in the new Father-Son
pair? ")
pairs[father] = son
print ("\nThe new pair of", father, "and", son, "have been added
to the list.")

else:
print ("Sorry, that father does not exist.  Try again.")
elif choice == "8":
print ("Find the grandson of a person in the list.")
grandfather = input("Which father do you want to look up to see if
he is a grandfather? ")
if grandfather in pairs:
father == pairs[grandfather]
for father in pairs:
grandson == pairs[father]
print (grandfather, "is the grandfather of", grandson, ".")
else:
print ("Sorry.", grandfather, "is not a grandfather.  Try
again.")



input ("\n\nPress the enter key to exit.\n")

Choice 8 gives me the following error...

Traceback (most recent call last):
  File "C:\Users\Public\Documents\My Python programs\father_son.py", line
105, in 
father == pairs[grandfather]
NameError: name 'father' is not defined

I thought father got defined in the

father == pairs[grandfather]
line.  I have tried it a couple different ways but always get the father is
not defined error once I enter the name.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mail

Re: [Tutor] Dictionaries - Using 1 Key:Value to find another

2010-12-11 Thread col speed
On 12 December 2010 07:10, Al Stern  wrote:

> This was another execise in my book.  Following is my code for a program
> that uses dictionaries to find and edit pairs of fathers and sons.  The
> program works right up to the final step which is to find out if any given
> father is actually a grandfather to someone else in the dictionary.  I set
> up multiple generations in the dictionary so there would be available
> matches.
>
> elif choice == "8":
> print ("Find the grandson of a person in the list.")
> grandfather = input("Which father do you want to look up to see if
> he is a grandfather? ")
> if grandfather in pairs:
> father == pairs[grandfather]
> for father in pairs:
> grandson == pairs[father]
> print (grandfather, "is the grandfather of", grandson, ".")
> else:
> print ("Sorry.", grandfather, "is not a grandfather.  Try
> again.")
>
>
>
> input ("\n\nPress the enter key to exit.\n")
>
> Choice 8 gives me the following error...
>
> Traceback (most recent call last):
>   File "C:\Users\Public\Documents\My Python programs\father_son.py", line
> 105, in 
> father == pairs[grandfather]
> NameError: name 'father' is not defined
>
> I thought father got defined in the
>
> father == pairs[grandfather]
> line.  I have tried it a couple different ways but always get the father is
> not defined error once I enter the name.
>
> I'm sure somebody has beaten me to it, but:
You have used "==" rather than "="
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dictionaries - Using 1 Key:Value to find another

2010-12-11 Thread David
On 12 December 2010 11:10, Al Stern  wrote:
>
> I thought father got defined in the
>
> father == pairs[grandfather]
> line.  I have tried it a couple different ways but always get the father is
> not defined error once I enter the name.

I only glanced at your code, but maybe you have some typos there:

father == pairs[grandfather]
for father in pairs:
grandson == pairs[father]

should probably be
father = pairs[grandfather]
for father in pairs:
grandson = pairs[father]

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


Re: [Tutor] Dictionaries - Using 1 Key:Value to find another

2010-12-11 Thread Al Stern
Ah.  Turns out I was just sloppy and/or stupid.  I realized I had another
error once I fixed the '==' part.

My new code which seems to work is...

elif choice == "8":
print ("Find the grandson of a person in the list.")
grandfather = input("Which father do you want to look up to see if
he is a grandfather? ")
if grandfather in pairs:
father = pairs[grandfather]
grandson = pairs[father] 
print (grandfather, "is the grandfather of", grandson, ".")
else:
print ("\nSorry.", grandfather, "is not a grandfather.  Try
again.")

Thanks all.
_
 
www.electronsbaseball.com

-Original Message-
From: David [mailto:bouncingc...@gmail.com] 
Sent: Saturday, December 11, 2010 6:35 PM
To: Al Stern
Cc: tutor@python.org
Subject: Re: [Tutor] Dictionaries - Using 1 Key:Value to find another

On 12 December 2010 11:10, Al Stern  wrote:
>
> I thought father got defined in the
>
> father == pairs[grandfather]
> line.  I have tried it a couple different ways but always get the father
is
> not defined error once I enter the name.

I only glanced at your code, but maybe you have some typos there:

father == pairs[grandfather]
for father in pairs:
grandson == pairs[father]

should probably be
father = pairs[grandfather]
for father in pairs:
grandson = pairs[father]

Try that.

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


Re: [Tutor] 'or' in assignment (not if statement)?

2010-12-11 Thread Lie Ryan
On 12/11/10 04:12, Alan Gauld wrote:
> "Steven D'Aprano"  wrote
>> As an experiment, offer to buy your wife dinner, and ask if she'd
>> prefer to go to an Italian or Chinese restaurant.
> 
> :-)
> She would either answer "Yes" (she would like to go to one of
> them, and if I'm lucky she might give me a clue which!) or "No"
> (she would prefer neither, Indian perhaps...)

The question "Would you like Italian or Chinese for dinner" is actually
a contraction of "Would you like Italian for dinner or would you like
Chinese for dinner". If we ask these two questions separately to the
wife, we get either "Yes or Yes", "Yes or No", "No or Yes", or "No or
No", which evaluates to either "Yes", "Yes", "Yes", and "No" (use "True"
or "False", if you prefer). Or syntactically:

===
I(i) = Italian (an object)
I(c) = Chinese (an object)
I(W) = Indication of Want (a unary relation)
---
W(i) or W(c)
===

In short circuiting language, that question is translated to: "If you
want Italian for dinner then answer Italian, else answer Chinese". Or
syntactically:

===
I(i) = Italian (an object)
I(c) = Chinese (an object)
I(W) = Indication of Want (a unary relation)
I(E) = Eat at (a unary relation)
---
if W(i) then i else c
--- or ---
if W(i) then Ei
if not W(i) then Ec
===

Neither of the two previous translations corresponds to the intuition we
had in natural language.

Instead, in natural language, the best translation is probably "If you
prefer Italian over Chinese for dinner then answer Italian, else if you
prefer Chinese over Italian for dinner then answer Chinese (assume she
cannot answer Neither or Both). Or syntactically:

===
I(i) = Italian (an object)
I(c) = Chinese (an object)
I(>) = Wife's Order of Preference (a strict weak order binary relation)
I(E) = Eat at (a unary relation)
---
if i > c then Ei
if c > i then Ec
===

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


Re: [Tutor] Code evaluation inside of string fails with __get_item

2010-12-11 Thread Steven D'Aprano

Tim Johnson wrote:


  I've never had the occasion to use assert() or any other
  python - shooting tools, any thoughts on that?



Assertions are a great tool, but never ever, under pain of great pain, 
use assert for testing user input or function arguments.


It's tempting to knock up a quick and dirty function like this:

def spam(n):
assert n >= 0, "amount of spam must be non-negative"
do_stuff_with(n)


Beware! This way leads to the Dark Side, or at least to strange and 
mysterious bugs that will only effect a few of your users and have you 
scratching your head.


The problem is that if you run Python with optimizations turned on, 
assertions are disabled. When run with python -O, your error checking 
disappears:


def spam(n):
do_stuff_with(n)

Strange and terrible things may now occur, exceptions being the *least* 
of your worries. Better to write explicit tests and give sensible errors:


def spam(n):
if n < 0:
raise ValueError("amount of spam must be non-negative")
do_stuff_with(n)


If you've ever written a comment like "This can't happen, but if it 
does, raise an exception", then you've essentially made an assertion. 
Here's a trivial example:


def spam(s):
s += " spam spam spam glorious SPAM!!!"
p = s.find("spam")
if p < 1:
# This can never happen!
raise RuntimeError("Serious internal error #123456")
do_something_with(p)

This could be written as:

def spam(s):
s += " spam spam spam glorious SPAM!!!"
p = s.find("spam")
assert p >= 1, "Serious internal error #123456"
do_something_with(p)


Now if you want to speed up your program by skipping all those "can 
never happen" tests, you can run python -O and the asserts will be 
compiled out.



Assertions are for testing program logic, not for testing user input. 
You should assume that the caller should never see your assertions: if 
the caller ever receives an AssertionError, you have failed. (If they 
receive a ValueError, or similar, that's *their* fault for passing 
rubbish input to your function.) Assertions are for making statements 
about *internal* state.


Having said that, sometimes it's hard to decide what counts as an 
internal state. Can function arguments ever be internal state? Sometimes 
I do things like this:


def ham(n):
if n < 0:
raise ValueError("amount of ham must be non-negative")
x = _common(n)
return "Ham is like spam but not as tasty." + x

def spam(n):
if n < 0:
raise ValueError("amount of spam must be non-negative")
x = _common(n)
return "Spam, glorious SPAM!!!" + x

def _common(n):
# Internal function.
assert n >= 0
do_stuff_here(n)
return something

Since _common is an internal function which the caller is not supposed 
to use directly, I feel it is acceptable to treat the input to _common 
as an internal state. If the caller wants to mess with my internal 
functions, they're responsible for whatever horrible things happen.


Another good example of assertions is for checking pre-conditions and 
post-conditions, particularly post-conditions. Here's a real example: in 
my stats module, I calculate "r", the Pearson's Correlation Coefficient. 
It doesn't matter what that means, but what does matter is that the 
result *must* be between -1 and 1, or else my code has a bug in it. Even 
though my code is perfectly bug-free *cough*, I end the function with 
the line:


assert -1.0 <= r <= 1.0

to ensure that if there is a bug in my code, it will raise an exception 
rather than return a garbage result. If the user wants to live 
dangerously, they can run with the optimization flag and skip my assertions.




  I am dealing with a programmatically composed format
  string, that originates from a source (html) file


Since the format string is generated by you, then errors in the format 
string are your responsibility, and they're an internal detail. Use 
assertions for checking the format string.


However, the HTML source is not an internal detail (at least I wouldn't 
expect it to be), it is *user* input, so any checks you do while 
processing the HTML should not use assertions.




  It may be 


  1)read from the file external to the object
and the source string passed into the object at instantiation.
The composed string is then translated correctly and
the embedded is evaluated.


Who makes that choice? You, or the caller? If the caller, then any 
errors that occur are not internal state, and you shouldn't use assert. 
If you, then it's an internal detail and you can use assert.





--
Steven

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


Re: [Tutor] Slicing Tuples

2010-12-11 Thread David Hutto
So, in essence, that would be redefining(in Python) basic division of
grammatical structures(splices)?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] role playing game - help needed

2010-12-11 Thread David Hutto
On Sat, Dec 11, 2010 at 11:54 AM, Lie Ryan  wrote:
> On 12/07/10 23:37, Robert Sjöblom wrote:
>> I've been told to use input() if I know that I'll only get integers,
>> and raw_input() for "everything."
>
> That is a bad piece of advice. You should only use input() when you can
> fully trust whoever doing the input (i.e. you).

Who uses the crap we, as noobies produce? It's pie in the sky
mentality. We design it because WE want it and WE(individually) use
it.

 input() can accept any
> python expressions, and this means the user can potentially execute
> malicious code as well.
>
 import subprocess
 input("input: ")
> input: subprocess.Popen(('ping', 'www.google.com'))
> 
 PING www.l.google.com (66.102.11.104) 56(84) bytes of data.
> 64 bytes from syd01s01-in-f104.1e100.net (66.102.11.104): icmp_req=1
> ttl=57 time=18.5 ms
>
> ___
> 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] Ressources for licensing

2010-12-11 Thread David Hutto
On Sat, Dec 11, 2010 at 9:52 AM, Knacktus  wrote:
> Hi everyone,
>
> can anybody recommend a lib or some other ressources about license
> mechanisms of desktop applications written in python. I'm thinking of a
> license-key that can be used to limit the time the application can be used.
> I also need to exploit the usage of a license server.


You probably need:

def license_this(self):
print "touch mine"

license_this(self)


>
> Cheers,
>
> Jan
> ___
> 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] 'or' in assignment (not if statement)?

2010-12-11 Thread Steven D'Aprano

Lie Ryan wrote:


The question "Would you like Italian or Chinese for dinner" is actually
a contraction of "Would you like Italian for dinner or would you like
Chinese for dinner". If we ask these two questions separately to the
wife, we get either "Yes or Yes", "Yes or No", "No or Yes", or "No or
No", which evaluates to either "Yes", "Yes", "Yes", and "No" (use "True"
or "False", if you prefer). Or syntactically:


In natural language (at least in English, other languages may have other 
conventions), "or" generally has a meaning closer to exclusive-or (xor) 
than to the logical disjunction (boolean "or"):


"We can go out, or we can stay home."
"Take the money, or the box."
"You must find the defendant guilty or not guilty."
"The cat is either inside the box, or outside the box."
"Your money, or your life."

You can't do both at the same time.

Even when the two alternatives aren't strictly contradictory, it's often 
assumed that only one will hold:


"Would you like tea or coffee?"

It would be surprising if somebody wanted both.

(Particularly if they were served in the same cup -- my wife once 
ordered a chai latte at a cafe. The waiter had no idea what that was, 
but must have known that "chai" means tea, and so mixed tea and coffee 
in the same cup and served it with milk. And yes, the result was as 
horrible as it sounds.)


We often make inclusivity an explicit choice:

"Dinner, or a movie, or both?"


Quoting from Websters Dictionary [1913]:

   A particle that marks an alternative; as, you may read or may
   write, -- that is, you may do one of the things at your
   pleasure, but not both. It corresponds to either. You may
   ride either to London or to Windsor. It often connects a
   series of words or propositions, presenting a choice of
   either; as, he may study law, or medicine, or divinity, or he
   may enter into trade.


Having said that, "or" in natural language is not precisely logical-xor 
either. I can't think of any natural question "would you like A or B?" 
where the answer "No" is appropriate if you would like both. Natural 
language is also far more flexible, and frequently allows choices that 
aren't explicitly enumerated:


Waiter: "Tea or coffee?"
Person A: "Nothing for me."
Person B: "Hot chocolate please."
Steve Martin: "I'll have a tall fair-trade organic half double-decaf 
half caf low-fat soy latte with a twist of lemon."

Logician: "Yes."


The reality is, there's no one-to-one correspondence between natural 
language constructs and boolean algebra.




--
Steven

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


Re: [Tutor] role playing game - help needed

2010-12-11 Thread Steven D'Aprano

David Hutto wrote:

On Sat, Dec 11, 2010 at 11:54 AM, Lie Ryan  wrote:

On 12/07/10 23:37, Robert Sjöblom wrote:

I've been told to use input() if I know that I'll only get integers,
and raw_input() for "everything."

That is a bad piece of advice. You should only use input() when you can
fully trust whoever doing the input (i.e. you).


Who uses the crap we, as noobies produce? It's pie in the sky
mentality. We design it because WE want it and WE(individually) use
it.


Do you want to learn good habits or learn bad habits? I think we've seen 
plenty of evidence on this mailing list that you have little interest in 
learning good habits, but actively defend your right learn bad habits.


There are plenty of people who do the same. They're harmless and even 
pathetically amusing as newbies, and then they get a job working as a 
professional programmer, and end up writing crappy, bug-addled code 
filled with the sort of n00b errors that we've been warning about. 
Bug-addled code with *real* consequences.


Command injection bugs are hugely common in the real world. At least 
four of the 25 most common security bugs in *professional* software are 
in my opinion varieties of the command injection flaw, and one of those 
is the SECOND most common flaw:


SQL injection attack #2 most common
Unrestricted upload of dangerous files #8 most common
OS command injection #9 most common
PHP file inclusion attack #13 most common

http://cwe.mitre.org/top25/

OS command injection is *exactly* the sort of thing we're warning about.

Feel free to continue learning bad habits, but please stop trying to 
encourage others to do the same.



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