Re: Inheriting Object

2011-05-20 Thread Ian Kelly
On Thu, May 19, 2011 at 10:11 PM, Navkirat Singh  wrote:
> Thanks Guys...I will look deeper into this. I thought I read somewhere that
> it was required in older python releases, but in newer releases it is not. I
> might be wrong though.

In Python 3.x all classes inherit from object by default, so "class
Foo(object):" and "class Foo:" are equivalent.  In Python 2.x they are
not equivalent, and you should use "class Foo(object):" unless you
have a specific reason not to.

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


Re: English Idiom in Unix: Directory Recursively

2011-05-20 Thread Roland Hutchinson
On Wed, 18 May 2011 07:19:08 +0200, Pascal J. Bourguignon wrote:

> Roland Hutchinson  writes:
> 
>> Sorry to have to contradict you,
> 
> Don't be sorry.
> 
> 
>> but it really is a textbook example of recursion.  Try this psuedo-code
>> on for size:
>>
>> FUNCTION DIR-DELETE (directory)
>>   FOR EACH entry IN directory
>>   IF entry IS-A-DIRECTORY THEN DIR-DELETE (entry).
>>
>> Well, now that's not just recursion; it's tail recursion.
> 
> It's not tail recursion.  If you had indented your code properly, you'd
> see why it's not:
> 
> (defun dir-delete (directory)
>   (loop for entry in directory
> do (if (is-a-directory entry)
>(dir-delete entry
> 

You are right, of course.  Thanks for the correction.

> (I put parentheses, so my editor knows what I mean and can do the
> indentation for me).

My editor would have done that, too--if I had bothered to be thinking 
clearly.

> That's why walking a directory is done with a recursive procedure,
> instead of an iterative one: it's much simplier.  To implement an
> iterative procedure, you would have to manage a stack yourself, instead
> of using the implicit stack of the recursive procedure.

Got it!  Thanks again.


-- 
Roland Hutchinson   

He calls himself "the Garden State's leading violist da gamba,"
... comparable to being ruler of an exceptionally small duchy.
--Newark (NJ) Star Ledger  ( http://tinyurl.com/RolandIsNJ ) 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: English Idiom in Unix: Directory Recursively

2011-05-20 Thread Steven D'Aprano
On Thu, 19 May 2011 22:13:14 -0700, rusi wrote:

> [I agree with you Xah that recursion is a technical word that should not
> be foisted onto lay users.]

I think that is a patronizing remark that under-estimates the 
intelligence of lay people and over-estimates the difficulty of 
understanding recursion.

Any person who has ever been to a barber or hairdresser with mirrors on 
two parallel walls will be familiar with recursion: a reflection of the 
reflection of the reflection of the reflection, forever.

In 1970, an extremely low-brow comedy "Carry On Up The Jungle" was about 
the search for an imaginary bird that flies in smaller and small circles 
until it disappears up it's own rear end, a type of recursion: 

http://en.wikipedia.org/wiki/Carry_On_Up_the_Jungle

The bird in question goes back in folklore since at least 1854:

http://en.wikipedia.org/wiki/Oozlum_bird


Trust me on this, if the audience of Carry On films could understand 
recursion, anyone can!



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


Re: obviscating python code for distribution

2011-05-20 Thread Steven D'Aprano
On Fri, 20 May 2011 05:48:50 +0100, Hans Georg Schaathun wrote:

> Either way, the assumption that your system will not be handled by
> idiots is only reasonable if you yourself is the only user.

Nonsense. How do you (generic "you", not any specific person) know that 
you are not an idiot?

If you are an idiot, you obviously shouldn't trust your own judgment -- 
although of course idiots do trust their own judgment when they 
shouldn't, and the less they know, the less they realise how little they 
know:

http://en.wikipedia.org/wiki/Dunning–Kruger_effect

So if you think that you're not an idiot, you might be an idiot who is 
unaware of being an idiot. Your own opinion is the last opinion you 
should pay attention to. The world is full of people with delusions of 
superiority -- only an idiot would trust their own opinion of themselves.

You can listen to others, but only so long as you don't surround yourself 
with idiots. But how do you know if the people around you are idiots? You 
certainly can't trust your judgment, nor can you trust theirs. If you're 
an idiot, you (still talking about generic "you") and your idiot friends 
are probably all congratulating yourselves for not being idiots.

In contrast, if you're not an idiot, then you probably are aware (and if 
not, you should be) of all the cognitive biases human beings are prone 
to, of all the mental and emotional weaknesses that we all suffer from, 
which cause us to act in idiotic ways. If you're not an idiot, then you 
know your limitations, that like everyone, you can be fooled or foolish, 
that you can make mistakes, that you sometimes operate equipment when you 
are not at the optimum level of alertness, when your attention to detail 
is below normal or you are a little more careless than you should be.

In short, that everyone, including yourself, can be an idiot, and the 
more intelligent you are, the more astonishingly stupid your mistakes may 
be. Any moron can accidentally burn themselves with a match, but it takes 
a first-class genius to give chronic lead poisoning to tens of millions 
*and* nearly destroy the ozone layer of the entire world:

http://en.wikipedia.org/wiki/Thomas_Midgley,_Jr.

So... if you think you are not an idiot, you are, and if you think you 
are an idiot, you are. Either way, even if your software is only being 
used by yourself, you should still attempt to make it as idiot-proof as 
an idiot like yourself can make it.



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


Re: English Idiom in Unix: Directory Recursively

2011-05-20 Thread Jonathan de Boyne Pollard

〈English Idiom in Unix: Directory Recursively〉
http://xahlee.org/comp/idiom_directory_recursively.html

--
English Idiom in Unix: Directory Recursively

Xah Lee, 2011-05-17

Today, let's discuss something in the category of lingustics.

You know how in unix tools, when you want to delete the whole
directory and all sub-directories and files in it, it's referred as
“recursive”?

[...]

Though, if you think about it, it's not exactly a correct description.
“Recursive”, or “recursion”, refers to a particular type of algorithm, 
[...]
Indeed. And the algorithms that are employed to perform the operations 
so described are recursive.



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


embedding and extending on windows

2011-05-20 Thread rusi
A client wants to 'be lectured' on extending and embedding python on
windows.
I am familiar with this (or was until python2.3 or thereabouts) on
linux -- never done it on windows.

Can some kind soul point me to some link on the issues/pitfalls re
this?

I see three choices:
1. Us MS C for the C extensions

2. Use cygwin
Recompile python from sources
Use gcc for the extensions

3. Mix gcc extension + precompiled python (and pray!)

-- If we use ctypes do we need to rely less on prayer?
-- What goes wrong with python compiled with gcc? [Ok let me guess I
have to compile everything else thereafter? Any other warnings?]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: English Idiom in Unix: Directory Recursively

2011-05-20 Thread Jonathan de Boyne Pollard
AFAICS what emacs calls "recursive delete" is what the ordinary person 
would simply call "delete". Presumably the non-recursive delete is 
called simply "delete" but is actually something more complicated than 
delete, and you're supposed to know what that is.


The "non-recursive delete" would be simply calling the rmdir() system 
call, which of course fails if the directory is non-empty.  One has to 
empty the directory of its contents, if any, first.  That, of course, 
involves potentially recursively removing any subdirectories, in exactly 
the same way.



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


Re: English Idiom in Unix: Directory Recursively

2011-05-20 Thread Chris Angelico
On Wed, 18 May 2011 12:59:45 -0500, Victor Eijkhout wrote:
> Recursion: (N). See recursion. See also tail recursion.

caching proxy (n): If you already know what recursion is, this is the
same. Otherwise, see recursion.

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


Re: obviscating python code for distribution

2011-05-20 Thread Steven D'Aprano
On Thu, 19 May 2011 17:56:12 -0700, geremy condra wrote:

> TL;DR version: large systems have indeed been verified for their
> security properties.

How confident are we that the verification software is sufficiently bug-
free that we should trust their results?

How confident are we that the verification software tests every possible 
vulnerability, as opposed to merely every imaginable one?


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


Re: hash values and equality

2011-05-20 Thread Ulrich Eckhardt
Ethan Furman wrote:
> Several folk have said that objects that compare equal must hash equal,
> and the docs also state this
> http://docs.python.org/dev/reference/datamodel.html#object.__hash__
> 
> I'm hoping somebody can tell me what horrible thing will happen if this
> isn't the case?

If you were familiar with what a hash map is, you wouldn't ask. The thing is 
that the hash is used to look up the place in the map where the thing is 
stored. If two equal objects have different hashes, they will be stored in 
different places in the hash map. Looking for object1 will then not turn up 
with object2, even though they are equal. If this is something you don't 
care about, and all you care about is identity, then I'd derive the hash 
from each object's ID.

This ID has another property which is something that is assumed for hashes, 
and your code seems a bit to get that wrong, too, and that is that the hash 
must not change. Again, the reason is that if the hash changes, the position 
in the hash map changes, too. If you then try to look up the changed object, 
it will look for it in the new place, but it won't be found because it is in 
the old place.

For that reason, it is generally useful to use immutable types like 
integers, floats, strings and tuples thereof as keys. Since you can't change 
them, you basically have the guarantee that they hash the same.

Uli

-- 
Domino Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Re: Faster Recursive Fibonacci Numbers

2011-05-20 Thread Ian Kelly
On Thu, May 19, 2011 at 11:58 PM, Steven D'Aprano
 wrote:
> Sure, which is why the above fib() function will become increasing
> inaccurate beyond some given n, by memory about n=71 or so. Er, at least
> the fib() function that *was* above until you deleted most of it :)
>
> If you want an *accurate* fib() function using exponentiation of φ, you
> need arbitrary precision non-integers.

This seems to work for arbitrary n, although I only tested it out to
about n=2000.

from decimal import Decimal, localcontext
from math import sqrt

def fib(n):
if n <= 70:
return fib_float(n)
else:
return fib_decimal(n)

phi_float = (1 + sqrt(5)) / 2
def fib_float(n):
numerator = (phi_float ** n) - (1 - phi_float) ** n
denominator = sqrt(5)
return int(round(numerator / denominator))

def fib_decimal(n):
with localcontext() as ctx:
ctx.prec = n // 4 + 1
sqrt_5 = Decimal('5').sqrt()
phi = (1 + sqrt_5) / 2
numerator = (phi ** n) - (1 - phi) ** n
return int((numerator / sqrt_5).to_integral_value())

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


Re: Faster Recursive Fibonacci Numbers

2011-05-20 Thread Ian Kelly
2011/5/20 Ian Kelly :
> def fib_decimal(n):
>    with localcontext() as ctx:
>        ctx.prec = n // 4 + 1
>        sqrt_5 = Decimal('5').sqrt()
>        phi = (1 + sqrt_5) / 2
>        numerator = (phi ** n) - (1 - phi) ** n
>        return int((numerator / sqrt_5).to_integral_value())

Note that I believe this is O(n) since the necessary precision grows
linearly with n.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: connect SIGINT to custom interrupt handler

2011-05-20 Thread Thomas 'PointedEars' Lahn
Christoph Scheingraber wrote:

> On 2011-05-15, Thomas 'PointedEars' Lahn  wrote:
>> Obviously.  `signal' refers to an `int' object, probably by something
>> like
>>
>>   signal = 42
>>
>> before.  E.g. `print' or a debugger will tell you, as you have not showed
>> the relevant parts of the code.
> 
> The problem is that I am running someone else's module which seems to
> use signal, I guess that means I have to create a child method?
> Is it correct anyway to have
> 
> signal.siginterrupt(signal.SIGINT, False)
> 
> in my custom interrupt_handler function

Only if `signal' is not the name of an int argument.

> or should it be outside but
> after signal.signal(signal.SIGINT, interrupt_handler)?

In the meantime, Chris Angelico has pointed out the cause of the problem.  
Please follow his advice, i.e. rename your argument.

-- 
PointedEars

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


Re: English Idiom in Unix: Directory Recursively

2011-05-20 Thread Jonathan de Boyne Pollard

I think what happens is that the “recursive” has become a idiom associated with 
directory to such a degree that the unix people don't know what the fuck they 
are talking about. They just simply use the word to go with directory whever 
they mean the whole directory.

In the emacs case: “Recursive delete of xx? (y or n) ”, what could it possibly 
mean by the word “recursive” there? Like, it might delete the
directory but not delete all files in it?


It might *try* to delete the directory but not any of its contents, 
yes.   If such functionality is not offered, then putting the word in 
the user interface is redundant, and possibly not the best way to warn 
the user of potentially a massive loss of files and directories.  But 
the algorithm employed is indeed recursive.


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


Re: os.access giving incorrect results on Windows

2011-05-20 Thread Tim Golden

On 19/05/2011 21:40, Andrew Berg wrote:

On 2011.05.19 03:08 PM, Tim Golden wrote:

* A R_OK check always succeeds if the file's attributes can be read
at all

So is this the same as F_OK then, or does it return false if the user
isn't allowed to read permissions?

* A W_OK check fails if the file has its DOS read-only attribute set

DOS attribute?

* A W_OK check always succeeds for a directory (because read-only means
something else for directories).

Would you care to propose some wording for the docs? I'm quite happy
to commit if we can come to an agreement.

I'm a beginner when it comes to Python, but I could give it a shot. A
big red warning box explaining how the code under Windows doesn't use
ACLs under the os.access() entry (above the notes) seems appropriate. A
warning box under os.W_OK saying something like "Under Windows, access()
will always indicate that a directory is writable." would also fit. You
know more about this than I do. I'm running Windows 7 right now and I
have a Python 3.2 interpreter window open if you want me to test/confirm
something. :-)


(Sorry; just got back to this this morning). I might raise this on 
python-dev. It seems to me that the docs for os.access:


  http://docs.python.org/library/os.html#os.access

are already fairly involved. And we try not to make the official
docs too confusing. That said, there's clearly an issue here,
albeit one which doesn't raise its head too often.

There's a case for re-assessing the patch I proposed in issue2528
to see whether to apply it appropriately (reworked).

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


Re: os.access giving incorrect results on Windows

2011-05-20 Thread Tim Golden

On 20/05/2011 09:21, Tim Golden wrote:

[... re os.access on Windows ...]


(Sorry; just got back to this this morning). I might raise this on
python-dev.


If you want to follow, my post is here:

  http://mail.python.org/pipermail/python-dev/2011-May/111530.html

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


Re: English Idiom in Unix: Directory Recursively

2011-05-20 Thread Hans Georg Schaathun
On 20 May 2011 06:55:35 GMT, Steven D'Aprano
   wrote:
:  On Thu, 19 May 2011 22:13:14 -0700, rusi wrote:
: 
: > [I agree with you Xah that recursion is a technical word that should not
: > be foisted onto lay users.]
: 
:  I think that is a patronizing remark that under-estimates the 
:  intelligence of lay people and over-estimates the difficulty of 
:  understanding recursion.

Could we then say that «recursion is a technical word that should
not /unnecessarily/ be foisted onto lay users»?


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


Re: obviscating python code for distribution

2011-05-20 Thread Hans Georg Schaathun
On 20 May 2011 07:04:27 GMT, Steven D'Aprano
   wrote:
:  On Fri, 20 May 2011 05:48:50 +0100, Hans Georg Schaathun wrote:
: 
: > Either way, the assumption that your system will not be handled by
: > idiots is only reasonable if you yourself is the only user.
: 
:  Nonsense. How do you (generic "you", not any specific person) know that 
:  you are not an idiot?

You don't, but if you are, you cannot trust any of the other assumptions
either, and making this assumption is reasonable by being less of a leap
than anything else you have done.

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


Re: English Idiom in Unix: Directory Recursively

2011-05-20 Thread Antti J Ylikoski

On 20.5.2011 3:38, Pascal J. Bourguignon wrote:

t...@sevak.isi.edu (Thomas A. Russ) writes:


"Pascal J. Bourguignon"  writes:


t...@sevak.isi.edu (Thomas A. Russ) writes:


This will only work if there is a backpointer to the parent.


No, you don't need backpointers; some cases have been mentionned in the
other answer, but in general:

 (defun parent (tree node)
(if (member node (children tree))
   tree
   (some (lambda (child) (parent child node)) (children tree

Yes, the question wasn't about time complexity.


  :-p

Um, this is a recursive function.  Inside PARENT, there is another call
to PARENT.


Feel free to derecursive it.



In the general case, to derecursive a function necessitates programming 
a stack, among other things.


Antti "Andy" Ylikoski

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


Re: obviscating python code for distribution

2011-05-20 Thread Disc Magnet
On Mon, May 16, 2011 at 9:06 AM, Littlefield, Tyler  wrote:
> I'm putting lots of work into this. I would rather not have some script
> kiddy dig through it, yank out chunks and do whatever he wants. I just want
> to distribute the program as-is, not distribute it and leave it open to
> being hacked.

Obfuscating the code won't help here. Remember, "the enemy knows the system."
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: starting a separate thread in maya

2011-05-20 Thread Andreas Tawn
> Hi,
> I'm using python2.5 in maya 2009 x64 (in linux).

For Maya/Python stuff you'll probably have more success at 
http://www.tech-artists.org/

Cheers,

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


Re: turn monitor off and on

2011-05-20 Thread Jack Krieger
> def turnOffMonitor():
>   SC_MONITORPOWER = 0xF170
>   win32gui.SendMessage(win32con.HWND_BROADCAST,
> win32con.WM_SYSCOMMAND, SC_MONITORPOWER, 2)

This code does not return control to you, so programm still locked. In my 
opinion it due broadcasting message. But I do not know how to send message to 
monitor directly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: turn monitor off and on

2011-05-20 Thread Leotis buchanan
@Astan

If you really want to turn your monitor on and off, you should probably try
pyserial are pyparrallel(http://pyserial.sourceforge.net/pyparallel.html),
along with a solid state relay. That worked for me on linux not sure about
windowXP,but it should work.

On Sat, May 14, 2011 at 1:08 AM, Astan Chee  wrote:

> Hi,
> I'm trying to turn off my monitor, pause and then turn it on again.
> I'm doing this in python 2.6 and windows xp. Here is my script so far
> (that doesn't work):
>
> import time
> import win32gui
> import win32con
> import win32api
>
> def turnOffMonitor():
>  SC_MONITORPOWER = 0xF170
>  win32gui.SendMessage(win32con.HWND_BROADCAST,
> win32con.WM_SYSCOMMAND, SC_MONITORPOWER, 2)
>
> def turnOnMonitor():
>  SC_MONITORPOWER = 0xF170
>  win32gui.SendMessage(win32con.HWND_BROADCAST,
> win32con.WM_SYSCOMMAND, SC_MONITORPOWER, -1)
>
> if __name__ == "__main__":
>  turnOffMonitor()
>  time.sleep(5)
>  turnOnMonitor()
>
> For some reason, the script doesn't turn the monitor back on. What am
> I doing wrong here or are there any other alternative?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Regards
Leotis Buchanan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Faster Recursive Fibonacci Numbers

2011-05-20 Thread SigmundV
There is a nice matrix representation of consecutive Fibonacci
numbers: [[1, 1], [1, 0]] ** n = [[F_n+1, F_n], [F_n, F_n-1]]. Using
the third party mpmath module, which uses arbitrary precision floating
point arithmetic, we can calculate the n'th Fibonacci number for an
arbitrary n as follows:

import mpmath
A = mpmath.matrix([[1, 1], [1, 0]])
F = A ** n

The n'th Fibonacci number is then found as the elements [0, 1] and [1,
0] in the matrix F.

This is more expensive than the formula involving the golden ratio,
but I like the compact representation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.access giving incorrect results on Windows

2011-05-20 Thread Ayaskanta Swain
Hi Tim,

 

Thanks for the reply and suggestions. I followed the patch provided by
you in issue 2528, but the code looks very tricky to me. Anyways I wrote
my Test.py script & tried only the def test_access_w(self): test case
which is defined under class FileTests(unittest.TestCase) by providing
my own directory path to check the write permissions on it.

 

I executed my But it failed with the following errors -

 

> python Test.py C:\temp\my_dir

test_access_w (__main__.FileTests) ... ERROR

 

==

ERROR: test_access_w (__main__.FileTests)

--

Traceback (most recent call last):

  File "Test.py", line 14, in test_access_w

f = os.open(dirpath, os.O_CREAT)

OSError: [Errno 13] Permission denied: 'C:\\temp\\my_dir'

 

--

Ran 1 test in 0.000s

 

FAILED (errors=1)

 

Basically the os.open() function is failing to open a directory (In this
case my_dir). The directory has write permissions for the user. Attached
herewith is my Test script. Can you please suggest some simple python
code which checks the write permissions of a directory in a straight
forward way (Not by using unit tests)

 

Thanks

Ayaskant-

Bangalore

 



Test.py
Description: Test.py
-- 
http://mail.python.org/mailman/listinfo/python-list


Python sets which support multiple same elements

2011-05-20 Thread ErichCart ErichCart
Many times when I am writing some program in python, I notice that I
could transform my list into set, then use the set methods like union,
intersection, set equality etc. , and it will solve my problem easily.
But then I realize that if I transform my list into set, it will
remove duplicates of elements in the list and so I will lose
information from my original list.

For example, I was writing a program to detect whether two strings are
anagrams of each other. I had to write it like this:

def isAnagram(w1, w2):
  w2=list(w2)
  for c in w1:
if c not in w2:
  return False
else:
  w2.remove(c)
  return True

But if there was a data structure in python which supported duplicate
elements(lets call it dset), then I could just write:

def inAnagram(w1,w2):
  return dset(w1)==dset(w2)

Example of some dset methods:
{1,2,3,3} intersection {4,1,2,3,3,3}  == {1,2,3,3}
{1,2,3,3} union {4,1,2,3,3,3} == {1,2,3,3,3,4}
{4,1,2,3,3,3} difference {1,2,3,3} == {4,3}

Do you think that it would be a good idea to add this kind of data
structure to python? Or did I overlook some other easy way to solve
this kind of problems?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python sets which support multiple same elements

2011-05-20 Thread Shunichi Wakabayashi
> Many times when I am writing some program in python, I notice that I
> could transform my list into set, then use the set methods like union,
> intersection, set equality etc. , and it will solve my problem easily.
> But then I realize that if I transform my list into set, it will
> remove duplicates of elements in the list and so I will lose
> information from my original list.
> 
> For example, I was writing a program to detect whether two strings are
> anagrams of each other. I had to write it like this:
> 
> def isAnagram(w1, w2):
>   w2=list(w2)
>   for c in w1:
> if c not in w2:
>   return False
> else:
>   w2.remove(c)
>   return True
> 
> But if there was a data structure in python which supported duplicate
> elements(lets call it dset), then I could just write:
> 
> def inAnagram(w1,w2):
>   return dset(w1)==dset(w2)
> 
> Example of some dset methods:
> {1,2,3,3} intersection {4,1,2,3,3,3}  == {1,2,3,3}
> {1,2,3,3} union {4,1,2,3,3,3} == {1,2,3,3,3,4}
> {4,1,2,3,3,3} difference {1,2,3,3} == {4,3}
> 
> Do you think that it would be a good idea to add this kind of data
> structure to python? Or did I overlook some other easy way to solve
> this kind of problems?

I think collections.Counter object may be useful for your purpose.

http://docs.python.org/py3k/library/collections.html#collections.Counter
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Python sets which support multiple same elements

2011-05-20 Thread Andreas Tawn
> For example, I was writing a program to detect whether two strings are
> anagrams of each other. I had to write it like this:
> 
> def isAnagram(w1, w2):
>   w2=list(w2)
>   for c in w1:
> if c not in w2:
>   return False
> else:
>   w2.remove(c)
>   return True
> 
> But if there was a data structure in python which supported duplicate
> elements(lets call it dset), then I could just write:
> 
> def inAnagram(w1,w2):
>   return dset(w1)==dset(w2)
> 
> Example of some dset methods:
> {1,2,3,3} intersection {4,1,2,3,3,3}  == {1,2,3,3}
> {1,2,3,3} union {4,1,2,3,3,3} == {1,2,3,3,3,4}
> {4,1,2,3,3,3} difference {1,2,3,3} == {4,3}
> 
> Do you think that it would be a good idea to add this kind of data
> structure to python? Or did I overlook some other easy way to solve
> this kind of problems?

Just to do the anagram problem you could do...

def isAnagram(w1, w2):
return sorted(w1) == sorted(w2)

To do the set-like operations, I guess that unless there's some itertools 
witchcraft available, you'd have to make your own dset type that inherits from 
list. Then you can define your own intersection/union etc. methods.

Cheers,

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


Re: Python sets which support multiple same elements

2011-05-20 Thread Chris Angelico
On Fri, May 20, 2011 at 9:37 PM, ErichCart ErichCart
 wrote:
> For example, I was writing a program to detect whether two strings are
> anagrams of each other. I had to write it like this:
>
> def isAnagram(w1, w2):
>  w2=list(w2)
>  for c in w1:
>    if c not in w2:
>      return False
>    else:
>      w2.remove(c)
>  return True

You may find it helpful to simply sort the lists, keeping them as
lists. If they're anagrams of each other, their sorted versions will
be equal.

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


Re: Python sets which support multiple same elements

2011-05-20 Thread ErichCart ErichCart
I see! How could I overlook sorting ))

It seems that collections.Counter is what I was talking about. It
seems to support all the set operations.

Also I realized that the data structure which i was describing is
called miltiset, and collections.Counter is python implementation of
multiset.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to get PID from subprocess library

2011-05-20 Thread TheSaint
Miki Tebeka wrote:

> The best module for doing such things is subprocess. And the Popen object
> has a pid attribute

I knew that, it's my fault that I'm not good to manage with popen. I found 
simplier to use subprocess.getstatusoutput. Maybe this function doesn't 
return the child pid, so I should adopt to work with Popen :(

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


Re: hash values and equality

2011-05-20 Thread MRAB

On 20/05/2011 07:33, Ulrich Eckhardt wrote:

Ethan Furman wrote:

Several folk have said that objects that compare equal must hash equal,
and the docs also state this
http://docs.python.org/dev/reference/datamodel.html#object.__hash__

I'm hoping somebody can tell me what horrible thing will happen if this
isn't the case?


If you were familiar with what a hash map is, you wouldn't ask. The thing is
that the hash is used to look up the place in the map where the thing is
stored. If two equal objects have different hashes, they will be stored in
different places in the hash map.

[snip]
Is this strictly true? I thought that the hash value, an integer, is
moduloed (Is that how you spell it? Looks weird!) with the number of
array elements to give an index into the array, so different hashes
could give the same index, and objects with different hashes could be
stored in the same 'bucket'.
--
http://mail.python.org/mailman/listinfo/python-list


Re: hash values and equality

2011-05-20 Thread Chris Angelico
On Sat, May 21, 2011 at 1:50 AM, MRAB  wrote:
> [snip]
> Is this strictly true? I thought that the hash value, an integer, is
> moduloed (Is that how you spell it? Looks weird!) with the number of
> array elements to give an index into the array, so different hashes
> could give the same index, and objects with different hashes could be
> stored in the same 'bucket'.

There can always be hash collisions between different objects, but the
assumption is that two identical objects will _always_ "collide".

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


Re: obviscating python code for distribution

2011-05-20 Thread geremy condra
On Fri, May 20, 2011 at 12:10 AM, Steven D'Aprano
 wrote:
> On Thu, 19 May 2011 17:56:12 -0700, geremy condra wrote:
>
>> TL;DR version: large systems have indeed been verified for their
>> security properties.
>
> How confident are we that the verification software is sufficiently bug-
> free that we should trust their results?

Pretty confident. Most formal verification systems are developed in
terms of a provably correct kernel bootstrapping the larger system.
The important thing is that since that kernel doesn't need to be
complete (only correct) it can typically be easily verified, and in
some cases exhaustively tested. There are also techniques which
generate certificates of correctness for verifiers that aren't
provably correct, but that isn't an area I know much about, and I
don't know if that gets used in practice. The bigger risk is really
that the model you're feeding it is wrong.

> How confident are we that the verification software tests every possible
> vulnerability, as opposed to merely every imaginable one?

Formal provers typically don't work by just throwing a bunch of input
at a piece of software and then certifying it. They take a set of
specifications (the model), a set of assumptions, and the program in
question, and provide a proof (in the mathematical sense) that the
program is exactly equivalent to the model given the assumptions.
Testing the assumptions and model are typically part of the
development process, though, and that's definitely a possible source
of errors.

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


Re: hash values and equality

2011-05-20 Thread Chris Kaynor
On Fri, May 20, 2011 at 9:20 AM, Chris Angelico  wrote:

> On Sat, May 21, 2011 at 1:50 AM, MRAB  wrote:
> > [snip]
> > Is this strictly true? I thought that the hash value, an integer, is
> > moduloed (Is that how you spell it? Looks weird!) with the number of
> > array elements to give an index into the array, so different hashes
> > could give the same index, and objects with different hashes could be
> > stored in the same 'bucket'.
>
> There can always be hash collisions between different objects, but the
> assumption is that two identical objects will _always_ "collide".


I think the question was: can this dummy code ever produce a set containing
less then itemCount items (for 0 < itemCount < 2**32)?

itemCount = 100

import itertools

counter = itertools.count().next

class Test(object):

def __init__(self):

self.hash = counter()

def __hash__(self):

 return self.hash

def __eq__(self, other):

return True


set((Test() for i in xrange(itemCount)))




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


Why did Quora choose Python for its development?

2011-05-20 Thread Beliavsky
I thought this essay on why one startup chose Python was interesting.

http://www.quora.com/Why-did-Quora-choose-Python-for-its-development

PHP was out of the question. Facebook is stuck on that for legacy
reasons, not because it's the best choice right now.[1] Our main
takeaway from that experience is that programming language choice is
very important and is extremely costly to change.

Python was a language that Charlie and I both knew reasonably well
(though I know it a lot better now than I did when we started). We
also briefly considered C#, Java, and Scala. The biggest issues with
Python are speed and the lack of typechecking.

C# seemed pretty promising. As a programming language, it's great,
but:

•We didn't want to be on the Microsoft stack. We were up for learning
something new, and MS SQL Server actually seemed pretty good, but we
knew we'd need to integrate with lots of open source code that has
only second-class support for .NET, if it supports it at all. Also,
most of the best engineers these days are used to open source stuff.
•We didn't want to take the risk of being on Mono (an open source
implementation of C#/.NET). It's not clear how long funding will be
around for that project, and I'd heard of various performance
problems. Plus, it seemed like everything else in the C# ecosystem
would assume we were on the Microsoft stack.

For a lot of little reasons, Java programs end up being longer and
more painful to write than the equivalent Python programs. It's also
harder to interoperate with non-Java stuff. Scala had a lot of the
downsides of Java and the JVM, although it wasn't quite as bad. The
language seemed a little too new and like it would bring some
unnecessary risk (for example, who knows how good will support be in
10 years).

Two other languages we very briefly thought about were OCaml and
Haskell (neither had big enough ecosystems or good enough standard
libraries, and both were potentially too hard for some designers/data
analysts/non-engineers who might need to write code).

We decided that Python was fast enough for most of what we need to do
(since we push our performance-critical code to backend servers
written in C++ whenever possible). As far as typechecking, we ended up
writing very thorough unit tests which are worth writing anyway, and
achieve most of the same goals. We also had a lot of confidence that
Python would continue to evolve in a direction that would be good for
the life of our codebase, having watched it evolve over the last 5
years.

So far, we've been pretty happy with the choice. There's a small
selection bias, but all of the employees who'd been working with other
languages in the past have been happy to transition to Python,
especially those coming from PHP. Since starting the following things
have happened:


•Python 2.6 got to the point where enough of the libraries we used
were compatible with it, and we made a very easy transition to it.
•Tornado (web framework) was released as open source, and we moved our
live updating web service to that.
•PyPy got to the point where it looks like it will eventually be
usable and will give us a significant speedup.

All together, these give us confidence that the language and ecosystem
is moving in a good direction.

[1] What are the horrors of PHP? and Do Facebook engineers enjoy
programming in PHP? and Why hasn't Facebook migrated away from PHP?
and What are some of the advantages of PHP over other programming
languages? for more on that.
Via Nizameddin Haşim Ordulu and JR Ignacio.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Faster Recursive Fibonacci Numbers

2011-05-20 Thread Steven D'Aprano
On Fri, 20 May 2011 16:54:06 +1000, Chris Angelico wrote:

> If someone has time to kill (as if!), it'd be awesome to get a new
> numeric type that uses bc's code; any other numeric type (int, long,
> float) could autopromote to it, removing the dilemma of which to promote
> out of long and float. Hmm... Python 4.0, 'bc' is the new default
> integer and everything else is a performance optimization? Heh.

The problem is, it isn't *just* a performance optimization, there is a 
semantic difference too. Consider:

>>> x = 1e-300
>>> x*x == 0
True

But using something with more precision:

>>> from fractions import Fraction
>>> x = Fraction(10)**-300
>>> x*x == 0
False


So you get different behaviour between floats and arbitrary precision 
numbers.



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


Re: English Idiom in Unix: Directory Recursively

2011-05-20 Thread rusi
On May 20, 1:48 pm, Hans Georg Schaathun  wrote:
> On 20 May 2011 06:55:35 GMT, Steven D'Aprano  
>  wrote:
>
> :  On Thu, 19 May 2011 22:13:14 -0700, rusi wrote:
> :
> : > [I agree with you Xah that recursion is a technical word that should not
> : > be foisted onto lay users.]
> :
> :  I think that is a patronizing remark that under-estimates the
> :  intelligence of lay people and over-estimates the difficulty of
> :  understanding recursion.
>
> Could we then say that «recursion is a technical word that should
> not /unnecessarily/ be foisted onto lay users»?

Yes.
Steven is talking about the fact that the intelligent lay user may be
intelligent.
I was referring to the fact that the intelligent lay user is a lay
user. [Not my main point except to say that dragging in
alt.usage.english into a discussion of recursion seemed a tad
unnecessary and unfair]

So the ILU may understand recursion
He may not know "recursion"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hash values and equality

2011-05-20 Thread Ethan Furman

Chris Rebert wrote:

On Thu, May 19, 2011 at 10:43 PM, Ethan Furman  wrote:

Several folk have said that objects that compare equal must hash equal, and
the docs also state this
http://docs.python.org/dev/reference/datamodel.html#object.__hash__

I'm hoping somebody can tell me what horrible thing will happen if this
isn't the case?  Here's a toy example of a class I'm thinking of writing
that will compare equal with int's, but hash differently:


This is the part considered "horrible":

--> d
{: '3',
 1: '1.0',
 2: '2.0',
 3: '3.0',
 : '2',
 : '1'}


Compare:

x = {5.0 : 'foo'}
x[5]

'foo'

Here's a more common/plausible "horrible" case closer to what the docs
writers had in mind:
--> class Naughty(object):
... def __init__(self, n):
... self.n = n
... def __eq__(self, other):
... return self.n == other.n
...
--> Naughty(5) == Naughty(5)
True
--> Naughty(5) is Naughty(5)
False
--> bad = Naughty(3)
--> y = {bad : 'foo'}
--> y[bad] # just happens to work
'foo'
--> del bad
--> # ok, how do we get to 'foo' now?
--> y[Naughty(3)] # try the obvious way
Traceback (most recent call last):
  File "", line 1, in 
KeyError: <__main__.Naughty object at 0x2a1cb0>
--> # We're screwed.

Naughty instances (and similar) can't be used sensibly as hash keys
(unless you /only/ care about object identity; this is often not the
case).


I tried this sequence (using Python 3, BTW -- forgot to mention that 
little tidbit -- sorry!):


--> del two
--> two
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'two' is not defined
--> d
{<__main__.Wierd object at 0x00C0C950>: '3',
 1: '1.0',
 2: '2.0',
 3: '3.0',
 <__main__.Wierd object at 0x00B3AC10>: '2',
 <__main__.Wierd object at 0x00B32E90>: '1'}
--> new_two = Wierd(2)
--> d[new_two]
'2'

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


Re: hash values and equality

2011-05-20 Thread Ethan Furman

Peter Otten wrote:

Ethan Furman wrote:


Several folk have said that objects that compare equal must hash equal,
and the docs also state this
http://docs.python.org/dev/reference/datamodel.html#object.__hash__

I'm hoping somebody can tell me what horrible thing will happen if this
isn't the case?  Here's a toy example of a class I'm thinking of writing
that will compare equal with int's, but hash differently:

--> class Wierd():
... def __init__(self, value):
... self.value = value
... def __eq__(self, other):
... return self.value == other
... def __hash__(self):
... return hash((self.value + 13) ** 3)
...


Try this:


d = {Wierd(1): 0}
1 in d

False

1 in d.keys()

True



My apologies -- I'm trying this in Python3:

--> two in d
True
--> two in d.keys()
True
-->
--> 2 in d
True
--> 2 in d.keys()
True

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


Re: obviscating python code for distribution

2011-05-20 Thread Nobody
On Fri, 20 May 2011 07:10:45 +, Steven D'Aprano wrote:

> How confident are we that the verification software tests every possible 
> vulnerability,

Formal verification is based upon mathematical proof, not empirical
results.

As Dijkstra said: "Program testing can be used to show the presence of
bugs, but never to show their absence".

For complex algorithms, it may be infeasible to cover even all of the
"interesting" cases, let alone a representative sample of all possible
cases. For concurrent (multi-threaded) code, it's often impractical to 
methodically test various interleavings.

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


List of WindowsError error codes and meanings

2011-05-20 Thread Andrew Berg
This is probably somewhat off-topic, but where would I find a list of
what each error code in WindowsError means? WindowsError is so broad
that it could be difficult to decide what to do in an except clause.
Fortunately, sys.exc_info()[1][0] holds the specific error code, so I
could put in an if...elif...else clause inside the except clause if I
needed to, but I don't know what all the different errors are.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hash values and equality

2011-05-20 Thread Ian Kelly
On Fri, May 20, 2011 at 10:36 AM, Chris Kaynor  wrote:
> I think the question was: can this dummy code ever produce a set containing
> less then itemCount items (for 0 < itemCount < 2**32)?

In CPython, no.  Even when you get a hash collision, the code checks
to see whether the hashes are actually equal before it calls the rich
comparison, the former check being a much faster operation since the
hash values are cached.

I'm not sure whether this can be counted on for all Python
implementations, though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: English Idiom in Unix: Directory Recursively

2011-05-20 Thread GSO
On 20 May 2011 18:21, rusi  wrote:

> On May 20, 1:48 pm, Hans Georg Schaathun  wrote:
> > On 20 May 2011 06:55:35 GMT, Steven D'Aprano  <
> steve+comp.lang.pyt...@pearwood.info> wrote:
> >
> > :  On Thu, 19 May 2011 22:13:14 -0700, rusi wrote:
> > :
> > : > [I agree with you Xah that recursion is a technical word that should
> not
> > : > be foisted onto lay users.]
> > :
> > :  I think that is a patronizing remark that under-estimates the
> > :  intelligence of lay people and over-estimates the difficulty of
> > :  understanding recursion.
> >
> > Could we then say that «recursion is a technical word that should
> > not /unnecessarily/ be foisted onto lay users»?
>
> Yes.
> Steven is talking about the fact that the intelligent lay user may be
> intelligent.
> I was referring to the fact that the intelligent lay user is a lay
> user. [Not my main point except to say that dragging in
> alt.usage.english into a discussion of recursion seemed a tad
> unnecessary and unfair]
>
> So the ILU may understand recursion
> He may not know "recursion"
> --
>
>
As a trainer there is an issue as to whether or not you should use words
that your trainees will not understand, the argument being that if you don't
use new words your trainees will not learn any new words.  It is also very
much a Unix philosophy that if you want idiots, feed them idiot food, so
think very carefully about what you put on the menu.  I think recursion was
very much a list processing concept for list processing languages.  I like
the purity of LISP, but COBOL for business applications any day.
-- 
http://mail.python.org/mailman/listinfo/python-list


TK program problem

2011-05-20 Thread bvdp
I've just done an update to my system here to Ubuntu 11.04. Mostly no
problems ... but I have an important (to me) python/TK program that's
stopped working. Well, it works ... mostly.

The python version is 2.7.1+ (no idea what the + means!).

I _think_ I have traced the problem to certain menus which call a
class. The calls appear to be ignored.

Basically, what I have is a line like:

bf = makeButtonBar(root, row=0, column=0, buttons=(
 ("Quit", self.quitall ),
 ("Stop", self.stopPmidi ),
 ("New Dir", self.chd),
 ("Load Playlist", self.playList),
 ("Favorites", selectFav),
 ("Options", setOptions) ) )

To create a menu bar. The function makeButtonBar() creates the buttons
with:

for txt, cmd in buttons:
Button(bf, text=txt, height=1, command=cmd).grid(column=c,
row=0, pady=5)


All this is fine (and worked perfectly before my upgrade). The menu
items which are ordinary functions continue to work. BUT the callbacks
which are classes are just ignored when they are clicked.

A cut from one of the ignored classes:


class selectFav:

def __init__(self):
...

And I've inserted some prints in the __init__() and nothing is
printed. Also, converted the class to new-style () but no change there
either.

Either python/tk has changed or my system is totally $*(#*#.
Suggestions welcome!

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


Re: hash values and equality

2011-05-20 Thread Ethan Furman

Ulrich Eckhardt wrote:

Ethan Furman wrote:

Several folk have said that objects that compare equal must hash equal,
and the docs also state this
http://docs.python.org/dev/reference/datamodel.html#object.__hash__

I'm hoping somebody can tell me what horrible thing will happen if this
isn't the case?


If you were familiar with what a hash map is, you wouldn't ask. The thing is 
that the hash is used to look up the place in the map where the thing is 
stored. If two equal objects have different hashes, they will be stored in 
different places in the hash map. Looking for object1 will then not turn up 
with object2, even though they are equal. 


In this case this is the behavior I want.

If this is something you don't 
care about, and all you care about is identity, then I'd derive the hash 
from each object's ID.


This won't work, as objects of the same type that compare equal should 
(and do, in my code) hash equal.


This ID has another property which is something that is assumed for hashes, 
and your code seems a bit to get that wrong, too, and that is that the hash 
must not change. 


The hash does not change on the instances, and is the same for all 
instances of my type that compare equal.


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


maybe useful : datetime conversion

2011-05-20 Thread Stef Mientki
hello,

using datetimes from a lot of different sources,
in many languages,
I had about 30 python helper routines,
which I now packed in one class,
much simpler.
Although I used the Delphi date-format as the base,
it shouldn't be difficult to rewrite the class for another type.

The input can be one of the following types :
  - None: the current date-time is used
  - 3.9 : a Delphi datetime
  - 3   : a Delphi datetime
  - "3.9"   : a Delphi datetime as a string
  - "3,9"   : a Delphi datetime as a (Dutch) string
  - "20-5-11"  : short year notation
  - "20-05-2011"   : long year notation
  - "2009-09-24 10:12:24"  : Access string
  - datetime.datetime ( 2011, 1, 15 )
  - time.struct_time
  - wx.DateTime
  - time.time()  (through method from_time)

Maybe someone can use it.

cheers,
Stef


import time
import datetime
import wx

Delphi_Date_0 = datetime.date ( *time.strptime ( '30-12-1899', '%d-%m-%Y' )[0:3]).toordinal()

# 
# 
class Delphi_Date ( float ) :
  def __new__ ( self, Something = None ) :
"""
Class meant to handle any datetime type, and converts it basically to
a Delphi DateTime (float: number of days since 1-1-1900).

The input can be one of the following types :
  - None: the current date-time is used
  - 3.9 : a Delphi datetime
  - 3   : a Delphi datetime
  - "3.9"   : a Delphi datetime as a string
  - "3,9"   : a Delphi datetime as a (Dutch) string
  - "20-5-11"  : short year notation
  - "20-05-2011"   : long year notation
  - "2009-09-24 10:12:24"  : Access string
  - datetime.datetime ( 2011, 1, 15 )
  - time.struct_time
  - wx.DateTime

with extra methods, also the following can be used
  - from_time   : time.time float

The following output methods are available
  - to_time ()
  - to_datetime ()
  - to_String ( self , Format = "%d-%m-%Y" )
  - to_String_Short ()
  - to_String_Date_Time_Short ()
  - to_String_Time_Short ()
  - to_String_Date_Time ()
  - to_wxTime ()
  - to_Iso ()
"""

# The current date-time is used, if no parameter is specified
if Something is None :
  Something = datetime.datetime.now ()

# floating point is assumed to be a Delphi datetime
# to specify a time.time float, use the method from_time
# Delphi_Date().from_time ( time.time()
# which is equivalent to
# Delphi_Date()
if isinstance ( Something, float ) :
  Value = Something

# sometimes a Delphi datetime is stored as an integer
elif isinstance ( Something, int ) :
  Value = Something

# A string can represent a lot of things
elif isinstance ( Something, basestring ) :

  # a float or integer,
  # also the Ducth notation where deceimal separator is a comma
  try :
Value = float ( Something.replace(',','.') )
  except :

# a string as a short year notation
try :
  Value = datetime.datetime.strptime ( Something, '%d-%m-%y' )
except ValueError :

  # a string as a long year notation
  try:
Value = datetime.datetime.strptime ( Something, '%d-%m-%Y' )
  except :

# a string as a (Dutch) Access notation
try :
  # Access string : "2009-09-24 00:00:00"
  Value =  datetime.datetime.strptime ( Something.split(' ')[0], "%Y-%m-%d" )
except :
  Value = Delphi_Date_0
  import traceback
  traceback.print_exc

Value = Value.toordinal() - Delphi_Date_0

# datetime.datetime ()
elif isinstance ( Something, datetime.datetime ) :
  Value = Something.toordinal() - Delphi_Date_0

# time.struct_time
elif isinstance ( Something, time.struct_time ) :
  Value = time.mktime ( Something )
  DT = datetime.datetime.fromtimestamp ( Value )
  Value = DT.toordinal() - Delphi_Date_0

# wx.DateTime
elif isinstance ( Something, wx.DateTime ) :
  DT = datetime.date ( Something.GetYear (),
   Something.GetMonth () + 1,
   Something.GetDay () )
  Value = DT.toordinal() - Delphi_Date_0

else :
  print type(Something), Something
  raise error ( 'aap' )

return float.__new__ ( self, Value )

  def from_time ( self, Time ) :
DT = datetime.datetime.fromtimestamp ( Time )
return Delphi_Date ( DT )


  def to_time ( self ):
return time.mktime ( self.to_datetime().timetuple() )

  def to_datetime ( self ) :
#return datetime.datetime.fromordinal ( int ( round ( self + Delphi_Date_0 )))
return datetime.datetime.fromordinal ( self + Delphi_Date_0 )

  def to_String ( self , Format = "%d-%m-%Y" ) :
DT = self.to_datetime()
try :
  return DT.strftime ( Format )
except :

Re: hash values and equality

2011-05-20 Thread Ethan Furman

Ethan Furman wrote:
Several folk have said that objects that compare equal must hash equal, 
and the docs also state this 
http://docs.python.org/dev/reference/datamodel.html#object.__hash__



Two things I didn't make clear originally:

I'm using Python3.

My objects (of type Wierd) obey the premise of comparing equal also 
meaning hashing equal (with other objects of type Wierd).


Perhaps my question could be narrowed down to:

Should the docs actually say that "objects of the same *type* that 
compare equal must hash equal", or is there an underlying reason that 
objects of *different types* that happen to compare equal *must not* 
have different hashes?


In other words, is the fact that everything tried so far in Python3 to 
break my toy code has failed to do so just an implementation detail of 
Python3?


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


Re: Faster Recursive Fibonacci Numbers

2011-05-20 Thread geremy condra
On Fri, May 20, 2011 at 10:07 AM, Steven D'Aprano
 wrote:
> On Fri, 20 May 2011 16:54:06 +1000, Chris Angelico wrote:
>
>> If someone has time to kill (as if!), it'd be awesome to get a new
>> numeric type that uses bc's code; any other numeric type (int, long,
>> float) could autopromote to it, removing the dilemma of which to promote
>> out of long and float. Hmm... Python 4.0, 'bc' is the new default
>> integer and everything else is a performance optimization? Heh.
>
> The problem is, it isn't *just* a performance optimization, there is a
> semantic difference too. Consider:
>
 x = 1e-300
 x*x == 0
> True
>
> But using something with more precision:
>
 from fractions import Fraction
 x = Fraction(10)**-300
 x*x == 0
> False
>
>
> So you get different behaviour between floats and arbitrary precision
> numbers.

And this shows up in the above implementation; reimplementing it using
Fractions and a truncated continuing fraction approximation of phi and
the square root of 5 gets us up to about 500, at the cost of a very
long computation time.

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


Re: hash values and equality

2011-05-20 Thread Chris Rebert
On Fri, May 20, 2011 at 10:56 AM, Ethan Furman  wrote:
> Chris Rebert wrote:
>> On Thu, May 19, 2011 at 10:43 PM, Ethan Furman  wrote:
>>> Several folk have said that objects that compare equal must hash equal,
>>> and
>>> the docs also state this
>>> http://docs.python.org/dev/reference/datamodel.html#object.__hash__
>>>
>>> I'm hoping somebody can tell me what horrible thing will happen if this
>>> isn't the case?

>> Here's a more common/plausible "horrible" case closer to what the docs
>> writers had in mind:
>> --> class Naughty(object):
>> ...     def __init__(self, n):
>> ...         self.n = n
>> ...     def __eq__(self, other):
>> ...         return self.n == other.n
>> ...
>> --> Naughty(5) == Naughty(5)
>> True
>> --> Naughty(5) is Naughty(5)
>> False
>> --> bad = Naughty(3)
>> --> y = {bad : 'foo'}
>> --> y[bad] # just happens to work
>> 'foo'
>> --> del bad
>> --> # ok, how do we get to 'foo' now?
>> --> y[Naughty(3)] # try the obvious way
>> Traceback (most recent call last):
>>  File "", line 1, in 
>> KeyError: <__main__.Naughty object at 0x2a1cb0>
>> --> # We're screwed.
>>
>> Naughty instances (and similar) can't be used sensibly as hash keys
>> (unless you /only/ care about object identity; this is often not the
>> case).
>
> I tried this sequence (using Python 3, BTW -- forgot to mention that little
> tidbit -- sorry!):

Doesn't matter anyway.

> --> del two
> --> two
> Traceback (most recent call last):
>  File "", line 1, in 
> NameError: name 'two' is not defined
> --> d
> {<__main__.Wierd object at 0x00C0C950>: '3',
>  1: '1.0',
>  2: '2.0',
>  3: '3.0',
>  <__main__.Wierd object at 0x00B3AC10>: '2',
>  <__main__.Wierd object at 0x00B32E90>: '1'}
> --> new_two = Wierd(2)
> --> d[new_two]
> '2'

Right, this is why I went to the trouble of writing Naughty instead of
using Wierd. Wierd's exact problem is less common and less severe. The
"equality implies identical hash" rule is not a universal one; some
other languages instead impose the lesser requirement of "equality and
same (or related) types implies identical hash". In Ruby for instance:
irb(main):001:0> 1 == 1.0
=> true
irb(main):002:0> a = {1.0 => 'hi'} # float key
=> {1.0=>"hi"}
irb(main):003:0> a[1] = 'bye' # int key
=> "bye"
irb(main):004:0> a # notice how they don't collide:
=> {1=>"bye", 1.0=>"hi"}
(Contrast this with my earlier analogous Python example.)

Basically, Naughty is fundamentally broken [hash(Naughty(2)) !=
hash(Naughty(2))], whereas Wierd merely defies convention [hash(2) !=
hash(Wierd(2)) but hash(Wierd(2)) == hash(Wierd(2))].

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


Re: hash values and equality

2011-05-20 Thread Christian Heimes
Am 20.05.2011 17:50, schrieb MRAB:
> Is this strictly true? I thought that the hash value, an integer, is
> moduloed (Is that how you spell it? Looks weird!) with the number of
> array elements to give an index into the array, so different hashes
> could give the same index, and objects with different hashes could be
> stored in the same 'bucket'.

I don't think 'moduloed' is an existing word but your description is
mostly correct. The hash of the object and length of the hash table are
used to calculate the position in the hash table. However Python's
implementation doesn't use buckets to reduce memory usage and pointer
dereferencing. If a slot in the hash table is already filled with an
object that is not equal to the new object (a collision), the hash is
shifted and the new slot is checked. The implementation detail is well
described in Modules/dictobject.c.

Christian

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


ABC validation strictly on an instance

2011-05-20 Thread Eric Snow
The current ABC implementation in Python implies that the class of a
conformant instance complies with the ABC.  The implication does not carry
down to the compliance of the instance itself.

This means that if you inherit from an ABC that has an abstract property,
your subclass must have a matching name to that property, or you will get a
TypeError.  (Same goes for abstract methods--a matching name must be bound,
even if not to a function).  For example:

class X(metaclass=ABCMeta):
@abstractproperty
def id(self): pass

class Y(X):
id = 1

class Z(X):
def __init__(self, id):
self._id = id
@property
def id(self):
return self._id

class Fail(X):
def __init__(self, id):
self.id = id

So classes Y and Z will work fine, but class Fail will raise a TypeError
when you instantiate [1] Fail, even though it "implemented" id in the
instance __init__ [2].  I looked at this all yesterday and did not see a
great way to approach this.  The best I could come up with was the
following:

class X(metaclass=ABCMeta):
@abstractproperty
def id(self): pass

@X.register
class Y:
def __init__(self, id):
self.id = id

So this is a promise that Y comforms to X without any of the automatic
validation.  However, you don't get _any_ validation.  You also lose any
otherwise inherited features, so it is more like an interface than an
abstract class.  I am not so sure about that above solution because it seems
like such a loose constraint.  I discussed the validation problem in another
email [1].

I am not sure if there is a way to bake into Python an effective check that
an instance (not the class of the instance) is compliant with an ABC.
 However, it would be cool if there was.  The current checking mechanism for
ABCs happens in object.__new__ at instantiation time.  At that point it has
no knowledge of what names your instance will have, other than those that
come from the class.

I spent a while looking at this whole problem yesterday and came up with a
bunch of approaches for that Fail situation above.  However, they mostly
seem like overkill to me.  I have included them below.  If anyone has  ideas
on how to approach the problem of using an ABC but satisfying it with
instance names, I would love to hear it.  Thanks!

-eric


[1] In this case it would be nice to know at definition time that the class
is missing the abstract "method".  You don't want an exception at definition
time for every subclass, though, since some you may want to keep abstract.
 I wrote up a decorator that allows you to validate at definition time in an
email yesterday (
http://mail.python.org/pipermail/python-list/2011-May/1272541.html).
[2] A related issue opened just yesterday: http://bugs.python.org/issue12128





1 - properties, with a getter and setter.  At definition time.  This seems
like overkill:

class X(object):
__metaclass__ = ABCMeta
@abstractproperty
def name(self): pass

class Y(X):
def __init__(self, name):
self._name = name
super(Y, self).__init__()
@property
def name(self):
return self._name
@name.setter
def name(self, val):
self._name = val

2 - getter/setter functions.  At definition time.  This does not guarantee
the name, only access around it:

class X(object):
__metaclass__ = ABCMeta
@abstractmethod
def get_name(self): pass
@abstractmethod
def set_name(self): pass

class Y(X):
def __init__(self, name):
self.name = name
super(Y, self).__init__()
def get_name(self):
return self.name
def set_name(self, val):
self.name = val

3 - descriptors directly.  At definition time.  Like the properties example:

class Name(object):
def __get__(self, obj, cls):
if obj is None:
return self
return obj._name
def __set__(self, obj, val):
obj._name = val

class X(object)
__metaclass__ = ABCMeta
@abstractproperty
def name(self): pass

class Y(X):
name = Name()
def __init__(self, name):
self.name = name
super(Y, self).__init__()

4 - getattribute.  At run time.  More overkill:

class Enforcer(object):
API = ()
def __getattribute__(self, attr):
if attr in API and attr not in dir(self):
raise TypeError("Expected attribute: %s" % attr)
return object.__getattribute__(self, attr)
def __setattr(self, attr, val):
if attr in API and attr not in dir(self):
raise TypeError("Expected attribute: %s" % attr)
object.__setattribute__(self, attr, val)

class X(Enforcer):
API = ("name",)

class Y(X):
def __init__(self, name):
self.name = name
super(Y, self).__init__()

5 - metaclass.  At instantiation time.  Overkill again:

class Enforcer(object):
class SomeMeta(type):
def enforces_API(f):
def __init__(self, *args, **kwa

Re: TK program problem

2011-05-20 Thread Ian Kelly
On Fri, May 20, 2011 at 12:03 PM, bvdp  wrote:
> All this is fine (and worked perfectly before my upgrade). The menu
> items which are ordinary functions continue to work. BUT the callbacks
> which are classes are just ignored when they are clicked.

I'm not a tk user, but it sounds like it has regressed from accepting
arbitrary callables as callbacks to accepting functions specifically.

What happens if you replace:

("Favorites", selectFav),

with:

("Favorites", lambda: selectFav()),
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-20 Thread Albert van der Horst
In article ,
Chris Angelico   wrote:
>On Sat, May 7, 2011 at 7:21 PM, Gregory Ewing
> wrote:
>> Hans Georg Schaathun wrote:
>>
>>> You cannot reference nor manipulate a reference in python, and that IMHO
>>> makes them more abstract.
>>
>> You can manipulate them just fine by moving them
>> from one place to another:
>
>I think "manipulate" here means things like pointer arithmetic, which
>are perfectly normal and common in C and assembly, but not in
>languages where they're references.

Adding an integer to a reference to an array element could have been
perfectly well-defined in Algol:
ref real operator+(ref real, int)
That is called overloading of the plus operator not "pointer arithmetic".
It is a misconception that these manipulation are dirty or ill-defined
or unsafe.

A similar extension would be possible in Python.
Allusion to assembler where one adds a number to a register
and can't tell whether the register contains an address or data
are misleading.

[This is not to say that I think it is advisable].

>
>Chris Angelico

Groetjes Albert.

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

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


Re: What other languages use the same data model as Python?

2011-05-20 Thread Albert van der Horst
In article <4dc7fa2f$0$29991$c3e8da3$54964...@news.astraweb.com>,
Steven D'Aprano   wrote:
>On Mon, 09 May 2011 12:52:27 +1200, Gregory Ewing wrote:
>
>> Steven D'Aprano wrote:
>>
>>> Since you haven't explained what you think is happening, I can only
>>> guess.
>>
>> Let me save you from guessing. I'm thinking of a piece of paper with a
>> little box on it and the name 'a' written beside it. There is an arrow
>> from that box to a bigger box.
>>
>> +-+
>>   +---+ | |
>> a | --+>| |
>>   +---+ | |
>> +-+
>>
>> There is another little box labelled 'b'. After executing 'a = b', both
>> little boxes have arrows pointing to the same big box.
>[...]
>> In this model, a "reference" is an arrow. Manipulating references
>> consists of rubbing out the arrows and redrawing them differently.
>
>All very good, but that's not what takes place at the level of Python
>code. It's all implementation. I think Hans Georg Schaathun made a good
>objection to the idea that "Python has references":
>
>In Pascal a pointer is a distinct data type, and you can
>have variables of a given type or of type pointer to that
>given type. That makes the pointer a concrete concept
>defined by the language.
>
>The same can't be said of "references" in Python. It's not part of Python
>the language, although it might be part of Python's implementation.
>
>
>
>> Also
>> in this model, a "variable" is a little box. It's *not* the same thing
>> as a name; a name is a label for a variable, not the variable itself.
>
>That's essentially the same model used when dealing with pointers. I've
>used it myself, programming in Pascal. The "little box" named a or b is
>the pointer variable, and the "big box" is the data that the pointer
>points to.
>
>It's not an awful model for Python: a name binding a = obj is equivalent
>to sticking a reference (a pointer?) in box a that points to obj.
>Certainly there are advantages to it.
>
>But one problem is, the model is ambiguous with b = a. You've drawn
>little boxes a and b both pointing to the big box (which I deleted for
>brevity). But surely, if a = 1234 creates a reference from a to the big
>box 1234, then b = a should create a reference from b to the box a?

There are cleaner languages. Algol 68 , Forth.
This is Forth.

VARIABLE A
VARIABLE B
1234 ( anonymous "object" created by the language )  A !
A @ B !( Copy the content, equivalent of B=A).

Algol 68
B:=A
compiler : THINK ! THINK !
A is a "ref int" so it can't be stored into b which is  a "ref int"
which is the name of a place where an int can be stored (not where
a ref int could be stored.)
Solution: Algol dereferences A into an int, by getting its content.
But it is a rule, very explicitly explained in the language definition.
(If you are that clean you can handle "ref ref int q" where q is the name
of a place where a "ref int" can be stored.)
"real a"  is in fact an abbreviation of "ref real a=loc real"
meaning "a" is a reference to a local real, that is anonymous.
The = means that the connection between a and that real is an identity,
i.e. the connection can't be broken. (Forget about C++,
"casting away const", yuck! )

In Forth and in Algol 68 storing a constant into a variable is
very different from copying the content of a variable to some
other variable.



>
>--
>Steven

Groetjes Albert

--
-- 
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

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


Re: List of WindowsError error codes and meanings

2011-05-20 Thread Genstein

On 20/05/2011 18:56, Andrew Berg wrote:

This is probably somewhat off-topic, but where would I find a list of
what each error code in WindowsError means?


Assuming it's a Win32 error code, winerror.h from the Platform SDK holds 
the answer. One version is linked below, it's in theory out of date 
(2003) but all the best known codes are present.


http://msdn.microsoft.com/en-us/library/ms819773.aspx
http://msdn.microsoft.com/en-us/library/ms819775.aspx

For example, "WindowsError [error 5] Access is denied" matches 
ERROR_ACCESS_DENIED (5L).


HRESULTS may also crop up (e.g. E_FAIL, 0x80040005) which are harder to 
list exhaustively since subsystems and COM components may roll their own 
codes of various sorts; but common ones are present in winerror.h.


All the best,

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


Re: hash values and equality

2011-05-20 Thread MRAB

On 20/05/2011 20:01, Christian Heimes wrote:

Am 20.05.2011 17:50, schrieb MRAB:

Is this strictly true? I thought that the hash value, an integer, is
moduloed (Is that how you spell it? Looks weird!) with the number of
array elements to give an index into the array, so different hashes
could give the same index, and objects with different hashes could be
stored in the same 'bucket'.


I don't think 'moduloed' is an existing word but your description is
mostly correct. The hash of the object and length of the hash table are
used to calculate the position in the hash table. However Python's
implementation doesn't use buckets to reduce memory usage and pointer
dereferencing. If a slot in the hash table is already filled with an
object that is not equal to the new object (a collision), the hash is
shifted and the new slot is checked. The implementation detail is well
described in Modules/dictobject.c.


A brief search on the web found a use of the word in 1982.
--
http://mail.python.org/mailman/listinfo/python-list


Re: List of WindowsError error codes and meanings

2011-05-20 Thread Tim Golden

On 20/05/2011 18:56, Andrew Berg wrote:

This is probably somewhat off-topic, but where would I find a list of
what each error code in WindowsError means? WindowsError is so broad
that it could be difficult to decide what to do in an except clause.
Fortunately, sys.exc_info()[1][0] holds the specific error code, so I
could put in an if...elif...else clause inside the except clause if I
needed to, but I don't know what all the different errors are.


Ultimately, only MSDN can tell you :)

But to be going on with, a combination of Python's built-in errno
module:

  http://docs.python.org/library/errno.html

and the pywin32 package's winerror module:


http://pywin32.hg.sourceforge.net/hgweb/pywin32/pywin32/file/236b256c13bf/win32/Lib/winerror.py

should help

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


Re: hash values and equality

2011-05-20 Thread Peter Otten
Ethan Furman wrote:

> Peter Otten wrote:
>> Ethan Furman wrote:
>> 
>>> Several folk have said that objects that compare equal must hash equal,
>>> and the docs also state this
>>> http://docs.python.org/dev/reference/datamodel.html#object.__hash__
>>>
>>> I'm hoping somebody can tell me what horrible thing will happen if this
>>> isn't the case?  Here's a toy example of a class I'm thinking of writing
>>> that will compare equal with int's, but hash differently:
>>>
>>> --> class Wierd():
>>> ... def __init__(self, value):
>>> ... self.value = value
>>> ... def __eq__(self, other):
>>> ... return self.value == other
>>> ... def __hash__(self):
>>> ... return hash((self.value + 13) ** 3)
>>> ...
>> 
>> Try this:
>> 
> d = {Wierd(1): 0}
> 1 in d
>> False
> 1 in d.keys()
>> True
>> 
> 
> My apologies -- I'm trying this in Python3:

Then you have to convert the keys to a list explicitly:

>>> class Weird:
... def __init__(self, value):
... self.value = value
... def __eq__(self, other):
... return self.value == other
... def __hash__(self):
... return hash((self.value + 13) **3)
...
>>> d = {Weird(1): 0}
>>> 1 in d
False
>>> 1 in d.keys()
False
>>> 1 in list(d.keys())
True


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


Re: obviscating python code for distribution

2011-05-20 Thread harrismh777

Steven D'Aprano wrote:

Nonsense. How do you (generic "you", not any specific person) know that
you are not an idiot?


lol Sum, ergo Idiot cogitat.


Reminds me of a philosophical story I heard one time from my religion 
professor...


... as it goes, De Carte leads his horse into town   ;-)  and having 
hitched it to the rail outside the local saloon and sauntering up to the 
bar,  the tender asks, "Would you be hav'in an ale sir?"


... De Carte replies, "I think not..." ... and then disappeared.


:)



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


Re: Why did Quora choose Python for its development?

2011-05-20 Thread Dotan Cohen
On Fri, May 20, 2011 at 19:39, Beliavsky  wrote:
> I thought this essay on why one startup chose Python was interesting.
>
> http://www.quora.com/Why-did-Quora-choose-Python-for-its-development
>
> PHP was out of the question. Facebook is stuck on that for legacy
> reasons, not because it's the best choice right now.[1] Our main
> takeaway from that experience is that programming language choice is
> very important and is extremely costly to change.
>
> Python was a language that Charlie and I both knew reasonably well
> (though I know it a lot better now than I did when we started). We
> also briefly considered C#, Java, and Scala. The biggest issues with
> Python are speed and the lack of typechecking.
>
> C# seemed pretty promising. As a programming language, it's great,
> but:
>
> •We didn't want to be on the Microsoft stack. We were up for learning
> something new, and MS SQL Server actually seemed pretty good, but we
> knew we'd need to integrate with lots of open source code that has
> only second-class support for .NET, if it supports it at all. Also,
> most of the best engineers these days are used to open source stuff.
> •We didn't want to take the risk of being on Mono (an open source
> implementation of C#/.NET). It's not clear how long funding will be
> around for that project, and I'd heard of various performance
> problems. Plus, it seemed like everything else in the C# ecosystem
> would assume we were on the Microsoft stack.
>
> For a lot of little reasons, Java programs end up being longer and
> more painful to write than the equivalent Python programs. It's also
> harder to interoperate with non-Java stuff. Scala had a lot of the
> downsides of Java and the JVM, although it wasn't quite as bad. The
> language seemed a little too new and like it would bring some
> unnecessary risk (for example, who knows how good will support be in
> 10 years).
>
> Two other languages we very briefly thought about were OCaml and
> Haskell (neither had big enough ecosystems or good enough standard
> libraries, and both were potentially too hard for some designers/data
> analysts/non-engineers who might need to write code).
>
> We decided that Python was fast enough for most of what we need to do
> (since we push our performance-critical code to backend servers
> written in C++ whenever possible). As far as typechecking, we ended up
> writing very thorough unit tests which are worth writing anyway, and
> achieve most of the same goals. We also had a lot of confidence that
> Python would continue to evolve in a direction that would be good for
> the life of our codebase, having watched it evolve over the last 5
> years.
>
> So far, we've been pretty happy with the choice. There's a small
> selection bias, but all of the employees who'd been working with other
> languages in the past have been happy to transition to Python,
> especially those coming from PHP. Since starting the following things
> have happened:
>
>
> •Python 2.6 got to the point where enough of the libraries we used
> were compatible with it, and we made a very easy transition to it.
> •Tornado (web framework) was released as open source, and we moved our
> live updating web service to that.
> •PyPy got to the point where it looks like it will eventually be
> usable and will give us a significant speedup.
>
> All together, these give us confidence that the language and ecosystem
> is moving in a good direction.
>
> [1] What are the horrors of PHP? and Do Facebook engineers enjoy
> programming in PHP? and Why hasn't Facebook migrated away from PHP?
> and What are some of the advantages of PHP over other programming
> languages? for more on that.
> Via Nizameddin Haşim Ordulu and JR Ignacio.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

They considered Haskell and OCaml and not a single mention of Perl?

-- 
Dotan Cohen

http://gibberish.co.il
http://what-is-what.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hash values and equality

2011-05-20 Thread Ethan Furman

Peter Otten wrote:

Ethan Furman wrote:


Peter Otten wrote:

Ethan Furman wrote:


Several folk have said that objects that compare equal must hash equal,
and the docs also state this
http://docs.python.org/dev/reference/datamodel.html#object.__hash__

--> class Wierd():
... def __init__(self, value):
... self.value = value
... def __eq__(self, other):
... return self.value == other
... def __hash__(self):
... return hash((self.value + 13) ** 3)
...

Try this:


d = {Wierd(1): 0}
1 in d

False

1 in d.keys()

True


My apologies -- I'm trying this in Python3:


Then you have to convert the keys to a list explicitly:


class Weird:

... def __init__(self, value):
... self.value = value
... def __eq__(self, other):
... return self.value == other
... def __hash__(self):
... return hash((self.value + 13) **3)
...

d = {Weird(1): 0}
1 in d

False

1 in d.keys()

False

1 in list(d.keys())

True


Ah!!  The light finally dawned!  Many thanks for everyone's input.

So if Wierd has a need to compare equal to some other type, it should 
implement a .equals() method.  Gotcha.


Likewise, if two different type's instances can compare equal, then for 
the most part they should be interchangeable.


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


Re: List of WindowsError error codes and meanings

2011-05-20 Thread Andrew Berg
On 2011.05.20 02:47 PM, Genstein wrote:
> On 20/05/2011 18:56, Andrew Berg wrote:
> > This is probably somewhat off-topic, but where would I find a list of
> > what each error code in WindowsError means?
>
> Assuming it's a Win32 error code, winerror.h from the Platform SDK holds 
> the answer. One version is linked below, it's in theory out of date 
> (2003) but all the best known codes are present.
>
> http://msdn.microsoft.com/en-us/library/ms819773.aspx
> http://msdn.microsoft.com/en-us/library/ms819775.aspx
>
> For example, "WindowsError [error 5] Access is denied" matches 
> ERROR_ACCESS_DENIED (5L).
I wasn't really sure if/how the codes in a WindowsError message mapped
to something I would find on MSDN. That's really helpful, and I actually
was able to find something more up-to-date:
http://msdn.microsoft.com/en-us/library/ms681381%28v=VS.85%29.aspx
> HRESULTS may also crop up (e.g. E_FAIL, 0x80040005) which are harder to 
> list exhaustively since subsystems and COM components may roll their own 
> codes of various sorts; but common ones are present in winerror.h.
That's good to know. Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TK program problem

2011-05-20 Thread bvdp

> I'm not a tk user, but it sounds like it has regressed from accepting
> arbitrary callables as callbacks to accepting functions specifically.
>
> What happens if you replace:
>
> ("Favorites", selectFav),
>
> with:
>
> ("Favorites", lambda: selectFav()),

Okay, this works. Great and thanks! Seems to me that the way I was
doing it should be alright ... and I've got some other programs
exhibiting the same problem.

Before I go "fixing" the issue ... is this known or even a bug?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TK program problem

2011-05-20 Thread Ian Kelly
On Fri, May 20, 2011 at 4:12 PM, bvdp  wrote:
> Okay, this works. Great and thanks! Seems to me that the way I was
> doing it should be alright ... and I've got some other programs
> exhibiting the same problem.
>
> Before I go "fixing" the issue ... is this known or even a bug?

The docs [1] say that a callback is a function, so I guess that if it
worked before it was just luck.  You should bring it up on the tkinter
list and see what they have to say about it, though.

I'm a bit confused about why you would want to use a class as a
callback anyway.  It looks like when the button is clicked it
instantiates the class and then throws it away?

[1] http://docs.python.org/library/tkinter.html#tk-option-data-types
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: obviscating python code for distribution

2011-05-20 Thread geremy condra
On Fri, May 20, 2011 at 1:24 PM, harrismh777  wrote:
> Steven D'Aprano wrote:
>>
>> Nonsense. How do you (generic "you", not any specific person) know that
>> you are not an idiot?
>
> lol     Sum, ergo Idiot cogitat.
>
>
> Reminds me of a philosophical story I heard one time from my religion
> professor...
>
> ... as it goes, De Carte leads his horse into town   ;-)  and having hitched
> it to the rail outside the local saloon and sauntering up to the bar,  the
> tender asks, "Would you be hav'in an ale sir?"
>
> ... De Carte replies, "I think not..."     ... and then disappeared.

At risk of being pedantic, I think you mean Descartes rather than De Carte.

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


Re: validating a class against an ABC at definition time

2011-05-20 Thread Eric Snow
On Thu, May 19, 2011 at 11:33 PM, Eric Snow wrote:

> Thinking about class APIs and validating a class against an API.  The abc
> module provides the tools to do some of this.  One thing I realized, that I
> hadn't noticed before, is that the abstractness of a class is measured when
> instances of the class are created.  This happens in object.__new__
> (pyobject.c).  Validating thus when a class is defined would not be as
> helpful, since there is no guarantee that the class is not meant to be
> abstract as well.
>
> However, I have found that it is sometimes nice to validate a class at
> definition time.  This is particularly true for a class that does not
> inherit from the abstract base class (but registers instead).
>
> Taking cues from abc.py and pyobject.c, here is a stab at a class decorator
> that validates a class against another.
>
> def validate(abc):
> if not isinstance(abc, type):
> raise TypeError("Can only validate against classes")
> def decorator(cls):
> if not __debug__:
> return cls
> if not isinstance(cls, type):
> raise TypeError("Can only validate classes")
> abstracts = set()
> for name in getattr(abc, "__abstractmethods__", set()):
> value = getattr(cls, name, None)
> if not value:
> abstracts.add(name)
> elif getattr(value, "__isabstractmethod__", False):
> abstracts.add(name)
> if abstracts:
> sorted_methods = sorted(abstracts)
> joined = ", ".join(sorted_methods)
> msg = "Class {} does not implement abstract methods {} of class
> {}"
> raise TypeError(msg.format(cls.__name__, joined, abc.__name__))
> return cls
> return decorator
>
> Stack this with the ABCMeta.register method and you can ensure that your
> class is compliant with the ABC at the time you register it on that ABC.
>
> Does anyone find this irrelevant or superfluous?  I know that it would be a
> good idea to stay on top of your class's implementation of an ABC's abstract
> methods.  However, this seems like a good way of doing that
> programmatically.
>
> Does anyone know a better way to do ABC validation at definition time?
>
> Thanks.
>
> -eric
>
>
>
>
>
I have revised this and made a recipe for it:

http://code.activestate.com/recipes/577711-validating-classes-and-objects-against-an-abstract/

The question remains of what alternatives exist to this solution.  Thanks!

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


Re: TK program problem

2011-05-20 Thread bvdp
Probably the fix is to use a function :)

> The docs [1] say that a callback is a function, so I guess that if it
> worked before it was just luck.  You should bring it up on the tkinter
> list and see what they have to say about it, though.
>
> I'm a bit confused about why you would want to use a class as a
> callback anyway.  It looks like when the button is clicked it
> instantiates the class and then throws it away?

I have no idea why I used a class like this, expect that it seemed to
work at the time. Yes, the class is instantiated when the button is
clicked. Then, the user stays in the class and uses its methods until
he hits  in the class.

So, I guess what's happening is that I'm treating the button click
much like a call to a new program/window which sets some options, etc.
in the main program.

You mention the tkinter group. Ummm, what group is that???

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


Re: TK program problem

2011-05-20 Thread Ian Kelly
On Fri, May 20, 2011 at 5:07 PM, bvdp  wrote:
> You mention the tkinter group. Ummm, what group is that???

http://tkinter.unpythonic.net/wiki/TkinterDiscuss
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TK program problem

2011-05-20 Thread bvdp
On May 20, 4:29 pm, Ian Kelly  wrote:
> On Fri, May 20, 2011 at 5:07 PM, bvdp  wrote:
> > You mention the tkinter group. Ummm, what group is that???
>
> http://tkinter.unpythonic.net/wiki/TkinterDiscuss

Thanks. New one for me. I'll subscribe and see if they know about
this.

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


Re: TK program problem

2011-05-20 Thread rantingrick
On May 20, 6:07 pm, bvdp  wrote:
> Probably the fix is to use a function :)
>
> > The docs [1] say that a callback is a function, so I guess that if it
> > worked before it was just luck.  You should bring it up on the tkinter
> > list and see what they have to say about it, though.
>
> > I'm a bit confused about why you would want to use a class as a
> > callback anyway.  It looks like when the button is clicked it
> > instantiates the class and then throws it away?
>
> I have no idea why I used a class like this, expect that it seemed to
> work at the time. Yes, the class is instantiated when the button is
> clicked. Then, the user stays in the class and uses its methods until
> he hits  in the class.

Thats sounds to me a lot like hammering square pegs though round
holes... Perhaps you should explain first in "plain english" what
problem your application is intended to solve, then how it is expected
to interact with the user, and finally, what exactly is NOT working
correctly. I would suffix such a documentary with the current source
code, verbatim.

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


Re: validating a class against an ABC at definition time

2011-05-20 Thread Eric Snow
On Fri, May 20, 2011 at 4:55 PM, Eric Snow wrote:

>
> I have revised this and made a recipe for it:
>
>
> http://code.activestate.com/recipes/577711-validating-classes-and-objects-against-an-abstract/
>
>
I also added this:

http://code.activestate.com/recipes/577712-adding-__implements__-to-subclasses-during-abcmeta/



> The question remains of what alternatives exist to this solution.  Thanks!
>
> -eric
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Faster Recursive Fibonacci Numbers

2011-05-20 Thread Chris Angelico
On Sat, May 21, 2011 at 3:07 AM, Steven D'Aprano
 wrote:
> On Fri, 20 May 2011 16:54:06 +1000, Chris Angelico wrote:
>
>> If someone has time to kill (as if!), it'd be awesome to get a new
>> numeric type that uses bc's code; any other numeric type (int, long,
>> float) could autopromote to it, removing the dilemma of which to promote
>> out of long and float. Hmm... Python 4.0, 'bc' is the new default
>> integer and everything else is a performance optimization? Heh.
>
> The problem is, it isn't *just* a performance optimization, there is a
> semantic difference too. Consider:

Sure, but I'm thinking here that the "gold standard" is accuracy, with
other types allowing a programmer to forfeit some accuracy in favour
of performance. (Oh, and I should have said "new default numeric
type".)

And, of course, I was thinking in a stupid hypothetical way that's
extremely unlikely ever to happen.

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


Re: hash values and equality

2011-05-20 Thread Steven D'Aprano
On Fri, 20 May 2011 21:17:29 +0100, MRAB wrote:

> On 20/05/2011 20:01, Christian Heimes wrote:
>> Am 20.05.2011 17:50, schrieb MRAB:
>>> Is this strictly true? I thought that the hash value, an integer, is
>>> moduloed (Is that how you spell it? Looks weird!) ...
>>
>> I don't think 'moduloed' is an existing word but your description is
>> mostly correct. ...
>>
> A brief search on the web found a use of the word in 1982.

All that means is that two people, three decades apart, used the same non-
word :)

I think you are treating "modulo" as a verb, equivalent to division, 
hence:

a/b => a is divided by b
a%b => a is "moduloed" by b

But modulo is not a verb. It is a preposition, a modifier word. Just as 
you might say "the cat sat on the mat" (cat on mat) or "the Princess 
found a pea underneath her mattress" (pea underneath mattress) so 
mathematicians will say "a is taken modulo b" (a modulo b).

English verbs nouns at the drop of a hat, but I've never heard of it 
verbing propositions:

"The princess underneathed the pea."

No, I don't think so.

English does use "remainder" as a verb, although not in the mathematical 
sense; I think that:

a%b => a is remaindered by b

is at least grammatical, although still ugly and awkward. I'm afraid that 
in English, the best way to say what you are trying to say is moderately 
verbose:

"the hash value, an integer, is taken modulo ..."


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


Python 2.6.7 release candidate 2 now available

2011-05-20 Thread Barry Warsaw
Hello to all you Pythoneers and Pythonistas,

I'm happy to announce the availability of Python 2.6.7 release candidate 2.
Release candidate 1 was not widely announced due to a mismatch between the
Mercurial and Subversion branches.  Barring any unforeseen issues, this will
be the last release candidate before 2.6.7 final, which is currently scheduled
for June 3, 2011.

As previously announced, Python 2.6 is in security-fix only mode.  This means
that general bug fix maintenance has ended, and only critical security fixes
are supported.  We will support Python 2.6 in security-fix only mode until
October 2013.  Also, this is a source-only release; no installers for Windows
or Mac OS X will be provided.

Please download and test this release candidate.

http://www.python.org/download/releases/2.6.7/

The NEWS file contains a list of changes since 2.6.6.

http://www.python.org/download/releases/2.6.7/NEWS.txt

Many thanks go out to the entire Python community for their contributions
great and small.

Enjoy,
-Barry
(on behalf of the Python development community)



signature.asc
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: obviscating python code for distribution

2011-05-20 Thread Steven D'Aprano
On Fri, 20 May 2011 15:45:03 -0700, geremy condra wrote:

> On Fri, May 20, 2011 at 1:24 PM, harrismh777 
> wrote:

>> ... as it goes, De Carte leads his horse into town   ;-)  and having
>> hitched it to the rail outside the local saloon and sauntering up to
>> the bar,  the tender asks, "Would you be hav'in an ale sir?"
>>
>> ... De Carte replies, "I think not..."     ... and then disappeared.
> 
> At risk of being pedantic, I think you mean Descartes rather than De
> Carte.

Being a drunken old fart, I can't imagine Descartes turning down an ale...

http://www.bbc.co.uk/dna/h2g2/A3651545



-- 
Steven

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


Re: hash values and equality

2011-05-20 Thread MRAB

On 21/05/2011 01:47, Steven D'Aprano wrote:

On Fri, 20 May 2011 21:17:29 +0100, MRAB wrote:


On 20/05/2011 20:01, Christian Heimes wrote:

Am 20.05.2011 17:50, schrieb MRAB:

Is this strictly true? I thought that the hash value, an integer, is
moduloed (Is that how you spell it? Looks weird!) ...


I don't think 'moduloed' is an existing word but your description is
mostly correct. ...


A brief search on the web found a use of the word in 1982.


All that means is that two people, three decades apart, used the same non-
word :)


[snip]
There were other uses. That's just the earliest one I found.
--
http://mail.python.org/mailman/listinfo/python-list


Re: hash values and equality

2011-05-20 Thread Steven D'Aprano
On Sat, 21 May 2011 02:02:48 +0100, MRAB wrote:

> On 21/05/2011 01:47, Steven D'Aprano wrote:
>> On Fri, 20 May 2011 21:17:29 +0100, MRAB wrote:
>>
>>> On 20/05/2011 20:01, Christian Heimes wrote:
 Am 20.05.2011 17:50, schrieb MRAB:
> Is this strictly true? I thought that the hash value, an integer, is
> moduloed (Is that how you spell it? Looks weird!) ...

 I don't think 'moduloed' is an existing word but your description is
 mostly correct. ...

>>> A brief search on the web found a use of the word in 1982.
>>
>> All that means is that two people, three decades apart, used the same
>> non- word :)
>>
> [snip]
> There were other uses. That's just the earliest one I found.


Nevertheless, it is still ungrammatical and incorrect usage. I'm not a 
prescriptivist, but not everything people write down is a word, otherwise 
we'd be forcefied to say evert typlo and mystake wsa an actul wrd.



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


Re: Python 2.6.7 release candidate 2 now available

2011-05-20 Thread harrismh777

Barry Warsaw wrote:

  We will support Python 2.6 in security-fix only mode until
October 2013.


Where can I read about the criteria for security-fix only?

Who decides whether the security fix is critical?


thanks,
kind regards,
m harris

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


Re: obviscating python code for distribution

2011-05-20 Thread harrismh777

Steven D'Aprano wrote:

... as it goes, De Carte leads his horse into town;-)and having
>>  hitched it to the rail outside the local saloon and sauntering up to
>>  the bar,  the tender asks, "Would you be hav'in an ale sir?"
>>
>>  ... De Carte replies, "I think not..." ... and then disappeared.

>
>  At risk of being pedantic, I think you mean Descartes rather than De
>  Carte.

Being a drunken old fart, I can't imagine Descartes turning down an ale...

http://www.bbc.co.uk/dna/h2g2/A3651545




.. .uh, yes...   playing on  'de carte before de horse...'



... as for Steven's link:

And Rene Descartes was a drunken old fart:
"I drink, therefore I am",

René Descartes (1596-1650)


I am not sure about Descartes drinking habits, but he was one true 
philosopher and mathematician...  so we honor him... with jokes !



:)


(how many of you guys are they going to be joking about 450 years from 
now ?)



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


Re: how to get PID from subprocess library

2011-05-20 Thread Kushal Kumaran
On Thu, May 19, 2011 at 9:32 PM, TheSaint  wrote:
> hello,
>
> I'm using to launch a program by subprocess.getstatusoutput. I'd like to
> know whether I can get the program ID, in order to avoid another launch.
>
> For clarity sake, I'm calling aria2 (the download manager for linux) and I
> wouldn't like to call one more instance of it. So what will I use to find
> the PID of the launched program?
>

The getstatusoutput function will only return when the command has
finished.  That's how it is able to give you the status.  So, if you
are using getstatusoutput, you will have only one instance of your
command running.

-- 
regards,
kushal
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Overuse of try/except/else?

2011-05-20 Thread Cameron Simpson
On 11May2011 13:37, James Mills  wrote:
| On Tue, May 10, 2011 at 7:34 PM, Jean-Michel Pichavant
|  wrote:
| > You can reraise the exception without loosing the stack trace.
| >
| > try:
| > ...
| > except SomeException, exc:
| > log(exc)
| > print 'Hello world'
| > raise # "raise exc" would loose the original stack trace
| 
| Valid point :) However I was referring to real experience
| where I've seen code that "catches all any any exception"
| and simply logs it.

I've put code like that in a worker thread occasionally, because there's
nobody "outside" to catch it; the submitter's attention is elsewhere.

These days I think I'd use a LateFunction (a facility of my own which is
a lot like the futures module) which returns a callable when you submit
a function; the worker thread runs the submitted function and catches the
return value or raised exception. Anyone who calls the returned callable
later gets the return value or the exception reraised as appropriate,
so one can avoid the dangerous "catch everything and log" scenario.

Cheers,
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

Observing the first balloon ascent in Paris, [Ben] Franklin heard a scoffer
ask, "What good is it?"  He spoke for a generation of scientists in
his retort, "What good is a newly born infant?" - John F. Kasson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.6.7 release candidate 2 now available

2011-05-20 Thread Ned Deily
In article ,
 harrismh777  wrote:
> Barry Warsaw wrote:
> >   We will support Python 2.6 in security-fix only mode until
> > October 2013. 
> Where can I read about the criteria for security-fix only?

You can read about the Python development cycle and security branches in 
the Python Developer's Guide:

   http://docs.python.org/devguide/devcycle.html#security-branches

> Who decides whether the security fix is critical?

Anyone can propose a security fix but the final decision is up to the 
release manager in charge of the branch.  For 2.6.x, that is Barry.

-- 
 Ned Deily,
 n...@acm.org

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