Re: Lambda question

2011-06-04 Thread Mel
jyoun...@kc.rr.com wrote:

> I was surfing around looking for a way to split a list into equal
> sections.  I came upon this algorithm:
>  
>>>> f = lambda x, n, acc=[]: f(x[n:], n, acc+[(x[:n])]) if x else acc
>>>> f("Hallo Welt", 3)
> ['Hal', 'lo ', 'Wel', 't']
>  
> http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-
evenly-s
> ized-chunks-in-python/312644
>  
> It doesn't work with a huge list, but looks like it could be handy in
> certain
> circumstances.  I'm trying to understand this code, but am totally lost. 
> I know a little bit about lambda, as well as the ternary operator, but how
> does this part work:
>  
>>>> f('dude'[3:], 3, []+[('dude'[:3])])
> ['dud', 'e']
>  
> Is that some sort of function call, or something else?  I'm guessing it
> works recursively?

Yeah, recursive.

f('dude', 3) 

evaluates to

f('e', 3, []+['dud']) if 'dude' else []

which evaluates to

f('', 3, []+['dud']+['e']) if 'e' else []+['dud']

which evaluates to

[]+['dud']+['e']

because the if...else finally takes the second branch since the x value is 
now an empty string.  

I've left the list additions undone .. tracing the actual data objects would 
show plain lists.  One of the disadvantages of lambdas is that you can't 
stick trace printouts into them to clarify what's happening.  Rewriting the 
thing as a plain def function would be instructive.

Mel.



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


Re: Dynamic Zero Padding.

2011-06-07 Thread Mel
Friedrich Clausen wrote:
> I want to print some integers in a zero padded fashion, eg. :
> 
>>>> print("Testing %04i" % 1)
> Testing 0001
> 
> but the padding needs to be dynamic eg. sometimes %05i, %02i or some
> other padding amount. But I can't insert a variable into the format
> specification to achieve the desirable padding.
> 
> I would be much obliged if someone can give me some tips on how to
> achieve a variably pad a number.

:)

('%%0%dd' % (pads,)) % (n,)

Probably be good to wrap it in a function.  It looks kind of obscure as it 
is.

Mel.

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


Re: How to form a dict out of a string by doing regex ?

2011-06-15 Thread Mel
Satyajit Sarangi wrote:

> 
> 
> data = "GEOMETRYCOLLECTION (POINT (-8.96484375
> -4.130859375000), POINT (2.021484375000 -2.63671875),
> POINT (-1.40625000 -11.162109375000), POINT
> (-11.95312500,-10.89843750), POLYGON
> ((-21.62109375 1.845703125000,2.46093750
> 2.197265625000, -18.98437500 -3.69140625,
> -22.67578125 -3.33984375, -22.14843750
> -2.63671875, -21.62109375
> 1.845703125000)),LINESTRING (-11.95312500
> 11.337890625000, 7.73437500 11.513671875000,
> 12.30468750 2.548828125000, 12.216796875000
> 1.669921875000, 14.501953125000 3.955078125000))"
> 
> This is my string .
> How do I traverse through it and form 3 dicts of Point , Polygon and
> Linestring containing the co-ordinates ?

Except for those space-separated number pairs, it could be a job for some 
well-crafted classes (e.g. `class GEOMETRYCOLLECTION ...`, `class POINT 
...`) and eval.

My approach would be to use a loop with regexes to recognize the leading 
element and pick out its arguments, then use the string split and strip 
methods beyond that point.  Like (untested):

recognizer = re.compile (r'(?(POINT|POLYGON|LINESTRING)\s*\(+(.*?)\)+,(.*)')
# regex is not good with nested brackets, 
# so kill off outer nested brackets..
s1 = 'GEOMETRYCOLLECTION ('
if data.startswith (s1):
data = data (len (s1):-1)

while data:
match = recognizer.match (data)
if not match:
break   # nothing usable in data
## now the matched groups will be:
## 1: the keyword
## 2: the arguments inside the smallest bracketed sequence
## 3: the rest of data
##  so use str.split and str.match to pull out the individual arguments,
## and lastly
data = match.group (3)

This is all from memory.  I might have got some details wrong in recognizer.

Mel.

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


Re: What's the best way to write this base class?

2011-06-18 Thread Mel
John Salerno wrote:
[ ... ]
> 1)
> class Character:
> def __init__(self, name, base_health=50, base_resource=10):
> self.name = name
> self.health = base_health
> self.resource = base_resource
> 
> 2)
> class Character:
> base_health = 50
> base_resource = 10
> def __init__(self, name):
> self.name = name
> self.health = base_health
> self.resource = base_resource
> 
> 3)
> BASE_HEALTH = 50
> BASE_RESOURCE = 10
> class Character:
> def __init__(self, name):
> self.name = name
> self.health = BASE_HEALTH
> self.resource = BASE_RESOURCE

For completeness, there's also 4)

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Character (object):
... health = 50
... def __init__ (self, name):
... self.name = name
... print self.name, self.health
... 
>>> Character ('Eunice')
Eunice 50


where the class attribute is used until it's overridden in the instance.

Mel.

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


Re: What's the best way to write this base class?

2011-06-20 Thread Mel
John Salerno wrote:

> On Jun 19, 8:52 pm, Chris Kaynor  wrote:
> 
>> Having a character class (along with possibly player character,
>> non-player character, etc), make sense; however you probably want to make
>> stuff like health, resources, damage, and any other attributes not be
>> handles by any classes or inheritance in order to allow you to make such
>> data-driven (ie, read from a file). Doing so makes the game much more
>> extendable: using classes, you are likely limited to 5 or 'combinations
>> and a few developers (plus, any designers need to know programming).
>>
>> A basic way to determine between using subclasses over a data driven
>> approach is: is there significantly different back-end behavior or merely
>> attribute differences.
> 
> Can you give a basic example of how this data-driven approach would
> work? You don't have to provide any code, just a description would be
> helpful. Such as, do I create a data file per character, and then have
> each character instance read/write to that file? Is it good to have so
> many files open at once, or would they only need to be read, closed,
> then opened again at the end to write?

Battle for Wesnoth is set up this way.  I don't know what the code does, but 
you can go wild creating new classes of character by mixing up new 
combinations of attribute settings in new configuration files, and injecting 
them into the standard game config files.

AFAIK you are stuck with the attributes the game is programmed for.  I've 
seen no way to create a new dimension for the game -- Conversation, for 
instance, with currently unknown attributes like vocabulary or tone.

Mel.

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


Re: How can I speed up a script that iterates over a large range (600 billion)?

2011-06-21 Thread Mel
John Salerno wrote:
> I'm working on the Project Euler exercises and I'm stumped on problem
> 3:
> 
> "What is the largest prime factor of the number 600851475143 ?"
[ ... ]
> Here is what I have so far. Initially the get_factors function just
> iterated over the entire range(2, n + 1), but since a number can't
> have a factor greater than half of itself, I tried to shorten the
> range by doing range(2, n //2), but that still leaves 300 billion
> numbers to go through.
> 
> def get_factors(number):
> factors = [number]
> 
> for n in range(2, number // 2):
> if number % n == 0:
> factors.append(n)
> 
> return factors
> 
> 
> def get_primes(number_list):
> primes = number_list[:]
> 
> for n in number_list:
> for x in range(2, n):
> if n % x == 0:
> primes.remove(n)
> break
> 
> return primes
> 
> 
> print(max(get_primes(get_factors(600851475143
> 
> 
> Also, I want to make it clear that I DO NOT WANT THE ANSWER. I really
> want to solve this myself, but the reason I'm asking about it is to
> see if there really is some way to change this code so that it can get
> an answer in less than one minute, as the website says should be
> possible. A hint about what I need to do would be nice, but not an
> answer. I just don't see any way to get the factors without iterating
> over the entire range of values, though.

It certainly can be done faster.  I ran it against the factor finder that I 
wrote, and it popped up the answer

mwilson@tecumseth:~$ bin/factors.py 600851475143
71 839 1471 ...

before I could glance at my watch.  factors.py works, as does yours, by 
testing for small factors first, but it divides them out as it goes, so it 
tends to do its work on smallish numbers.  And since the smallest factors 
are taken out as soon as possible, they have to be the prime ones.

Good hunting,   Mel.

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


Re: Handling import errors

2011-06-21 Thread Mel
Guillaume Martel-Genest wrote:

> What is the pythonic way to handle imports error? What is bugging me
> is that the imports can't be inside a function (because I use them in
> different places in the script and thus they have to be in the global
> scope).

Actually, you can if you declare them global:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
... global os
... import os
... 
>>> dir (os)
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'os' is not defined
>>> f()
>>> dir (os)
['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 
'EX_NOINPUT', 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 
'EX_PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE', 
'F_OK', 'NGROUPS_MAX', 'O_APPEND', 'O_ASYNC', 'O_CREAT', 'O_DIRECT', 
'O_DIRECTORY', 'O_DSYNC', 'O_EXCL', 'O_LARGEFILE', 'O_NDELAY', 'O_NOATIME', 
'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK

etc.

Mel.

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


Re: sorry, possibly too much info. was: Re: How can I speed up a script that iterates over a large range (600 billion)?

2011-06-21 Thread Mel
John Salerno wrote:

> ::sigh:: Well, I'm stuck again and it has to do with my get_factors
> function again, I think. Even with the slight optimization, it's
> taking forever on 20! (factorial, not excitement)  :) It's frustrating
> because I have the Python right, but I'm getting stuck on the math.
> 
> The problem:
> 
> "What is the smallest positive number that is evenly divisible by all
> of the numbers from 1 to 20?"
> 
> 
> 
> Here's the function (it's in the problem3.py file, hence the import
> below):
> 
> import math
> 
> def get_factors(number):
> factors = []
> 
> for n in range(2, int(math.sqrt(number))):
> if number % n == 0:
> factors.append(n)
> factors.append(number // n)
> 
> return factors
> 
> And here's my new script for the new exercise:
> 
> import math
> from problem3 import get_factors
> 
> max_num = 20
> n = math.factorial(max_num)
> factors = get_factors(n)
> div_all = []
> 
> for x in factors:
> for y in range(2, max_num+1):
> if x % y != 0:
> break
> elif y == max_num:
> div_all.append(x)
> 
> print(min(div_all))
> 
> It could easily be that I'm simply approaching it all wrong. I just
> thought that maybe using the factorial of the highest number in the
> range (in this case, 20) would be an easy way of finding which numbers
> to test.

These are almost "trick questions" in a way, because of the math behind 
them.  If the question were "What is the tallest high-school student in 
Scranton, PA?" then searching a population for the property would be the 
only way to go.  BUT you can also build up the answer knowing the 
factorization of all the numbers up to 20.

Mel.

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


Re: writable iterators?

2011-06-22 Thread Mel
Steven D'Aprano wrote:

> On Wed, 22 Jun 2011 15:28:23 -0400, Neal Becker wrote:
> 
>> AFAICT, the python iterator concept only supports readable iterators,
>> not write. Is this true?
>> 
>> for example:
>> 
>> for e in sequence:
>>   do something that reads e
>>   e = blah # will do nothing
>> 
>> I believe this is not a limitation on the for loop, but a limitation on
>> the python iterator concept.  Is this correct?
> 
> Have you tried it? "e = blah" certainly does not "do nothing", regardless
> of whether you are in a for loop or not. It binds the name e to the value
> blah.
> 
>>>> seq = [1, 2]
>>>> for e in seq:
> ... print(e)
> ... e = 42
> ... print(e)
> ...
> 1
> 42
> 2
> 42
> 
> 
> I *guess* that what you mean by "writable iterators" is that rebinding e
> should change seq in place, i.e. you would expect that seq should now
> equal [42, 42]. Is that what you mean? It's not clear.
> 
> Fortunately, that's not how it works, and far from being a "limitation",
> it would be *disastrous* if iterables worked that way. I can't imagine
> how many bugs would occur from people reassigning to the loop variable,
> forgetting that it had a side-effect of also reassigning to the iterable.
> Fortunately, Python is not that badly designed.

And for an iterator like

def things():
yield 1
yield 11
yield 4
yield 9

I don't know what it could even mean.

Mel.

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


Re: Significant figures calculation

2011-06-28 Thread Mel
Erik Max Francis wrote:

> Chris Angelico wrote:
>> On Tue, Jun 28, 2011 at 12:56 PM, Steven D'Aprano
>>  wrote:
>>> Zero sig figure: 0
> 
> That's not really zero significant figures; without further
> qualification, it's one.
> 
>> Is 0.0 one sig fig or two?
> 
> Two.
> 
>> (Just vaguely curious. Also curious as to
>> whether a zero sig figures value is ever useful.)
> 
> Yes.  They're order of magnitude estimates.  1 x 10^6 has one
> significant figure.  10^6 has zero.

By convention, nobody ever talks about 1 x 9.97^6 .

Mel.

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


Re: Significant figures calculation

2011-06-28 Thread Mel
Erik Max Francis wrote:

> Mel wrote:
>> Erik Max Francis wrote:
>> 
>>> Chris Angelico wrote:
>>>> On Tue, Jun 28, 2011 at 12:56 PM, Steven D'Aprano
>>>>  wrote:
>>>>> Zero sig figure: 0
>>> That's not really zero significant figures; without further
>>> qualification, it's one.
>>>
>>>> Is 0.0 one sig fig or two?
>>> Two.
>>>
>>>> (Just vaguely curious. Also curious as to
>>>> whether a zero sig figures value is ever useful.)
>>> Yes.  They're order of magnitude estimates.  1 x 10^6 has one
>>> significant figure.  10^6 has zero.
>> 
>> By convention, nobody ever talks about 1 x 9.97^6 .
> 
> Not sure what the relevance is, since nobody had mentioned any such thing.
> 
> If it was intended as a gag, I don't catch the reference.

I get giddy once in a while.. push things to limits.  It doesn't really mean 
anything.  The point was that it's only the 2 in a number like 2e6 that is 
taken to have error bars.  The 6 is always an absolute number.  As is the 10 
in 2*10**6.  The thought also crossed my mind of a kind of continued 
fraction in reverse -- 2e1.3e.7 .  I managed to keep quiet about that one.

Mel.

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


Re: Implicit initialization is EXCELLENT

2011-07-05 Thread Mel
Steven D'Aprano wrote:
[ ... ]
> Python generally follows this design. Apart from files, I can't easily
> think off the top of my head of any types that require a separate
> open/start/activate call before they are usable. It's also relevant to
> tkinter, which will implicitly create a root window for you when needed.
> Since you can't do anything without a root window, I don't see the benefit
> in forcing the user to do so. When they need to learn about root windows,
> they will in their own good time.

In wx, many of the window classes have Create methods, for filling in 
various attributes in "two-step construction".  I'm not sure why, because it 
works so well to just supply all the details when the class is called and an 
instance is constructed.  Maybe there's some C++ strategy that's being 
supported there.

Mel.

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


Re: Implicit initialization is EXCELLENT

2011-07-06 Thread Mel
Ian Kelly wrote:

> On Wed, Jul 6, 2011 at 12:49 AM, Ulrich Eckhardt
>  wrote:
>> Mel wrote:
>>> In wx, many of the window classes have Create methods, for filling in
>>> various attributes in "two-step construction".  I'm not sure why,
>>> because it works so well to just supply all the details when the class
>>> is called and an instance is constructed.  Maybe there's some C++
>>> strategy that's being supported there.
>>
>> Just guessing, is it legacy, C-with-classes code rather than C++ code
>> perhaps? Haven't looked at wx for a while. Such code typically lacks
>> understanding of exceptions, which are the only way to signal failure
>> from e.g. constructors.
> 
> No, wx is C++ through and through.  For the why of it, see:
> 
> http://wiki.wxpython.org/TwoStageCreation
> 
> The "More Details" section is particularly illuminating.

Yes, it is.  Many thanks.

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


Re: Does hashlib support a file mode?

2011-07-06 Thread Mel
Phlip wrote:

> If I call m = md5() twice, I expect two objects.
> 
> I am now aware that Python bends the definition of "call" based on
> where the line occurs. Principle of least surprise.

Actually, in

def file_to_hash(path, m = hashlib.md5()):

hashlib.md5 *is* called once; that is when the def statement is executed.

Later on, when file_to_hash gets called, the value of m is either used as 
is, as the default parameter, or is replaced for the duration of the call by 
another object supplied by the caller.

Mel.



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


Re: more advanced learning resources (code structure, fundamentals)

2011-07-07 Thread Mel
John [H2O] wrote:
[ ... ]
> What are the key points to the classes? Is it okay to reference or pass
> classes to instantiate a class? 

Yes.  The standard library does this in BaseHTTPServer (via its parent 
SocketServer.)  Maybe looks abstruse at the outset, but it's the natural way 
to assign a fresh message handler to a new input message.  Docs are via the 
Python Global Module Index, source is in some directory like
/usr/lib/python2.6/SocketServer.py , .../BaseHTTPServer.py , etc.

Mel.

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


Re: None versus MISSING sentinel -- request for design feedback

2011-07-15 Thread Mel
Steven D'Aprano wrote:

> Well yes, but None is an explicit missing value too. The question I have
> is if I should support None as that value, or something else. Or if anyone
> can put a good case for it, both, or neither and so something completely
> different.

If it's any help, I think (some of?) the database interface packages already 
do just that, returning None when they find NULL fields.


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


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread Mel
Andrew Berg wrote:
> I should also mention that this mostly speculation on my part, and that
> I would love to hear from someone who develops for these devices.

There's a mailing list for Python scripting on Android -- 
List-Subscribe: <http://groups.google.com/group/python-for-
android/subscribe?hl=en_US>, <mailto:python-for-
android+subscr...@googlegroups.com> 
. Tends to be pretty detail-oriented.

Mel.

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


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread Mel
Andrew Berg wrote:
> I should also mention that this mostly speculation on my part, and that
> I would love to hear from someone who develops for these devices.

There's a mailing list for Python scripting on Android -- 
List-Subscribe: <http://groups.google.com/group/python-for-
android/subscribe?hl=en_US>, <mailto:python-for-
android+subscr...@googlegroups.com> 
. Tends to be pretty detail-oriented.

Mel.

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


Re: I am fed up with Python GUI toolkits...

2011-07-20 Thread Mel
sturlamolden wrote:
> On 20 Jul, 11:59, Thomas Jollans  wrote:

>> It is perfectly reasonable to be required to manually call some sort of
>> destroy() method to tell the toolkit what you no longer want the user to
>> see

> Yes, but not to avoid a memory leak.

OTOH, if you intend to re-use the Dialog object, it's not a memory leak.

Mel.

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


Re: Observations on the three pillars of Python execution

2011-08-05 Thread Mel
Steven D'Aprano wrote:

> There may be some other obscure built-in type that includes code objects,
> but I can't imagine what it would be. I feel confident in saying that
> functions, and functions alone, contain code. Even methods are just
> wrappers around functions. Even built-in functions like len don't contain
> code! (Or at least, their code isn't accessible from Python.) Which makes
> sense, if you think about it: their code is part of the Python virtual
> machine, not the object.

Interesting question.  Iterators seem to have code objects:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1, 2, 3]
>>> b = (x for x in a)
>>> dir(b)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', 
'__hash__', '__init__', '__iter__', '__name__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', 
'__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'next', 
'send', 'throw']
>>> for name in dir(b):
...   print name, type (getattr (b, name))
... 
__class__ 
__delattr__ 
__doc__ 
__format__ 
__getattribute__ 
__hash__ 
__init__ 
__iter__ 
__name__ 
__new__ 
__reduce__ 
__reduce_ex__ 
__repr__ 
__setattr__ 
__sizeof__ 
__str__ 
__subclasshook__ 
close 
gi_code 
gi_frame 
gi_running 
next 
send 
throw 


in the form of the gi_code attribute.  No idea what it's for, although no 
reason to believe it shouldn't be there.  (Very interesting demo you gave of 
primitive object creation.  I' awed.)

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


Re: pairwise combination of two lists

2011-08-17 Thread Mel
Yingjie Lin wrote:
> I have two lists:
> 
> li1 = ['a', 'b']
> li2 = ['1', '2']
> 
> and I wish to obtain a list like this
> 
> li3 = ['a1', 'a2', 'b1', 'b2']
> 
> Is there a handy and efficient function to do this, especially when li1
> and li2 are long lists.
> I found zip() but it only gives [('a', '1'), ('b', '2')],  not exactly
> what I am looking for.

This seems to do it :

mwilson@tecumseth:~$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import itertools
>>> li1 = ['a', 'b']
>>> li2 = ['1', '2']
>>> map (lambda (x,y):x+y, list (itertools.product (li1, li2)))
['a1', 'a2', 'b1', 'b2']


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


Re: pairwise combination of two lists

2011-08-17 Thread Mel
Mel wrote:

> Yingjie Lin wrote:
>> I have two lists:
>> 
>> li1 = ['a', 'b']
>> li2 = ['1', '2']
>> 
>> and I wish to obtain a list like this
>> 
>> li3 = ['a1', 'a2', 'b1', 'b2']
[ ... ]
> This seems to do it :
> 
> mwilson@tecumseth:~$ python
> Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
> [GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import itertools
>>>> li1 = ['a', 'b']
>>>> li2 = ['1', '2']
>>>> map (lambda (x,y):x+y, list (itertools.product (li1, li2)))
> ['a1', 'a2', 'b1', 'b2']


I have doubts about this in Python3, since tuple unpacking in a argument 
list isn't done there, and I don't think sum works on strings.  Some other 
function can probably be made to work.

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


Re: try... except with unknown error types

2011-08-19 Thread Mel
xDog Walker wrote:
> On Friday 2011 August 19 12:09, Yingjie Lin wrote:
[ ... ]
>> Does anyone know what error type I should put after the except statement?
>> or even better: is there a way not to specify the error types? Thank you.
> 
> You probably need to import urllib2 before you can use urllib2.HTTPError.
> 
> Otherwise, you can try using the base class:
> 
> except Exception, e:

There are maybe better base classes to use.  Running the interpreter:
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib2
>>> help (urllib2.HTTPError)

will show you

class HTTPError(URLError, urllib.addinfourl)
 |  Raised when HTTP error occurs, but also acts like non-error return
 |  
 |  Method resolution order:
 |  HTTPError
 |  URLError
 |  exceptions.IOError
 |  exceptions.EnvironmentError
 |  exceptions.StandardError
 |  exceptions.Exception
 |  exceptions.BaseException
> 

So catching any of urllib2.HTTPError, urllib2.URLError, IOError, 
EnvironmentError, or StandardError will detect the exception -- with 
increasing levels of generality.

Mel.

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


Re: is there any principle when writing python function

2011-08-23 Thread Mel
smith jack wrote:

> i have heard that function invocation in python is expensive, but make
> lots of functions are a good design habit in many other languages, so
> is there any principle when writing python function?

It's hard to discuss in the abstract.  A function should perform a 
recognizable step in solving the program's problem.  If you prepared to 
write your program by describing each of several operations the program 
would have to perform, then you might go on to plan a function for each of 
the described operations.  The high-level functions can then be analyzed, 
and will probably lead to functions of their own.

Test-driven development encourages smaller functions that give you a better 
granularity of testing.  Even so, the testable functions should each perform 
one meaningful step of a more general problem.

> for example, how many lines should form a function?
Maybe as few as one.

def increase (x, a):
return x+a

is kind of stupid, but a more complicated line

def expand_template (bitwidth, defs):
'''Turn Run-Length-Encoded list into bits.'''
return np.array (sum (([bit]*(count*bitwidth) for count, bit in 
defs), []), np.int8)

is the epitome of intelligence.  I wrote it myself.  Even increase might be 
useful:

def increase (x, a):
return x + a * application_dependent_quantity

`increase` has become a meaningful operation in the imaginary application 
we're discussing.


For an upper bound, it's harder to say.  If you read to the end of a 
function and can't remember how it started, or what it did in between, it's 
too big.  If you're reading on your favourite screen, and the end and the 
beginning are more than one page-scroll apart, it might be too big.  If it's 
too big, factoring it into sub-steps and making functions of some of those 
sub-steps is the fix.

Mel.

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


Re: Mastering Python... Best Resources?

2011-08-26 Thread Mel
Chris Angelico wrote:
[ ... ]
> You can get books on algorithms from all sorts of places, and with a
> very few exceptions, everything you learn with apply to Python and
> also to every other language you use.

I liked _Programming Pearls_ by Jon Bentley.  No reference to Python -- that 
would be the O.P.'s job.

Mel.

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


Re: Python fails on math

2011-02-24 Thread Mel
D'Arcy J.M. Cain wrote:
> On Thu, 24 Feb 2011 04:56:46 -0800
> Ethan Furman  wrote:

>> > That's a big if though. Which languages support such a thing? C doubles
>> > are 64 bit, same as Python.
>> 
>> Assembly!  :)
> 
> Really?  Why would you need that level of precision just to gather all
> the students into the auditorium?

You would think so, but darned if some of them don't wind up in a 
*different* *auditorium*!

Mel.

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


Re: ImSim: Image Similarity

2011-03-05 Thread Mel
n00m wrote:

> 
> I uploaded a new version of the subject with a
> VERY MINOR correction in it. Namely, in line #55:
> 
> print '%12s %7.2f' % (db[k][1], db[k][0] / 3600.0,)
> 
> instead of
> 
> print '%12s %7.2f' % (db[k][1], db[k][0] * 0.001,)
> 
> I.e. I normalized it to base = 100.
> Now the values of similarity can't be greater than 100
> and can be treated as some "regular" percents (%%).
> 
> Also, due to this change, the *empirical* threshold of
> "system alarmity" moved down from "number 70" to "20%".
> 
>   bears2.jpg
> 
>   bears2.jpg0.00
>   bears3.jpg   15.37
>   bears1.jpg   19.13
> sky1.jpg   23.29
> sky2.jpg   23.45
>  ff1.jpg   25.37
>lake1.jpg   26.43
>   water1.jpg   26.93
>  ff2.jpg   28.43
>   roses1.jpg   31.95
>   roses2.jpg   36.12

I'd like to see a *lot* more structure in there, with modularization, so the 
internal functions could be used from another program.  Once I'd figured out 
what it was doing, I had this:


from PIL import Image
from PIL import ImageStat

def row_column_histograms (file_name):
'''Reduce the image to a 5x5 square of b/w brightness levels 0..3
Return two brightness histograms across Y and X
packed into a 10-item list of 4-item histograms.'''
im = Image.open (file_name)
im = im.convert ('L')   # convert to 8-bit b/w
w, h = 300, 300
im = im.resize ((w, h))
imst = ImageStat.Stat (im)
sr = imst.mean[0]   # average pixel level in layer 0
sr_low, sr_mid, sr_high = (sr*2)/3, sr, (sr*4)/3
def foo (t):
if t < sr_low: return 0
if t < sr_mid: return 1
if t < sr_high: return 2
return 3
im = im.point (foo) # reduce to brightness levels 0..3
yhist = [[0]*4 for i in xrange(5)]
xhist = [[0]*4 for i in xrange(5)]
for y in xrange (h):
for x in xrange (w):
k = im.getpixel ((x, y))
yhist[y / 60][k] += 1
xhist[x / 60][k] += 1
return yhist + xhist


def difference_ranks (test_histogram, sample_histograms):
'''Return a list of difference ranks between the test histograms and 
each of the samples.'''
result = [0]*len (sample_histograms)
for k, s in enumerate (sample_histograms):  # for each image
for i in xrange(10):# for each histogram slot
for j in xrange(4): # for each brightness level
result[k] += abs (s[i][j] - test_histogram[i][j])   
return result


if __name__ == '__main__':
import getopt, sys
opts, args = getopt.getopt (sys.argv[1:], '', [])
if not args:
args = [
'bears1.jpg',
'bears2.jpg',
'bears3.jpg',
'roses1.jpg',
'roses2.jpg',
'ff1.jpg',
'ff2.jpg',
'sky1.jpg',
'sky2.jpg',
'water1.jpg',
'lake1.jpg',
]
test_pic = 'bears2.jpg' 
else:
test_pic, args = args[0], args[1:]

z = [row_column_histograms (a) for a in args]
test_z = row_column_histograms (test_pic)

file_ranks = zip (difference_ranks (test_z, z), args)   
file_ranks.sort()

print '%12s' % (test_pic,)
print ''
for r in file_ranks:
print '%12s %7.2f' % (r[1], r[0] / 3600.0,)



(omitting a few comments that wrapped around.)  The test-case still agrees 
with your archived version:

mwilson@tecumseth:~/sandbox/im_sim$ python image_rank.py bears2.jpg *.jpg
  bears2.jpg

  bears2.jpg0.00
  bears3.jpg   15.37
  bears1.jpg   19.20
sky1.jpg   23.20
sky2.jpg   23.37
 ff1.jpg   25.30
   lake1.jpg   26.38
  water1.jpg   26.98
 ff2.jpg   28.43
  roses1.jpg   32.01


I'd vaguely wanted to do something like this for a while, but I never dug 
far enough into PIL to even get started.  An additional kind of ranking that 
takes colour into account would also be good -- that's the first one I never 
did.

Cheers, Mel.

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


Re: ImSim: Image Similarity

2011-03-05 Thread Mel
n00m wrote:

> As for using color info...
> my current strong opinion is: the colors must be forgot for good.
> Paradoxically but "profound" elaboration and detailization can/will
> spoil/undermine the whole thing. Just my current imo.

Yeah.  I guess including color info cubes the complexity of the answer.  
Might be too complicated to know what to do with an answer like that.

Mel.

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


Re: my computer is allergic to pickles

2011-03-07 Thread Mel
Bob Fnord wrote:

> I want a portable data file (can be moved around the filesystem
> or copied to another machine and used), so I don't want to use
> mysql or postgres. I guess the "sqlite" approach would work, but
> I think it would be difficult to turn the tuples of strings and
> lists of strings and numbers into database table lines.

This is as hairy as it's ever got for me (untested):

def inserter (db, table_name, names, values):
query = 'INSERT INTO %s (%s) VALUES (%s)' % (table_name, ','.join 
(names), ','.join (['?'] * len (names)))
cur = db.cursor()
cur.execute (query, values)
cur.close()
#...
for v in all_value_triples:
inserter (db, 'some_table', ['f1', 'f2', 'f3'], v)

(or even write a bulk_inserter that took all_value_triples as an argument 
and moved the `for v in ...` inside the function.)

> Would a database in a file have any advantages over a file made
> by marshal or shelve?

Depends.  An sqlite3 database file is usable by programs not written in 
Python.

> I'm more worried about the fact that a python program in user
> space can bring down the computer!

Never been a problem in the programs I've written.

Mel.

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


Re: ImSim: Image Similarity

2011-03-07 Thread Mel
n00m wrote:

> But funny thing takes place.
> At first thought it's a false-positive: some modern South East
> Asian town and a lake somewhere in Russia, more than 100 years
> ago. Nothing similar in them?
> 
> On both pics we see:
> -- a lot of water on foreground;
> -- a lot of blue sky at sunny mid-day;
> -- a bit of light white clouds in the sky;
> 
> In short,
> the notion of similarity can be speculated about just endlessly.

Exactly.  That's the kind of similarity I would call valid.  That's what my 
algorithms, if I ever finished writing any, would be looking for.

Mel.

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


Re: Coding and Decoding in Python

2011-03-17 Thread Mel
Wanderer wrote:

> I have a dll that to communicate with I need to send numeric codes. So
> I created a dictionary. It works in one direction in that I can
> address the key and get the value. But when the program returns the
> value I can't get the key. This code is very simple and I could use a
> list and the index except for the last value. Is there a better way to
> handle coding and decoding values to strings?
> 
> QCam_Info = {
> 'qinfCameraType' : 0,# Camera model (see
> QCam_qcCameraType)
> 'qinfSerialNumber': 1,# Deprecated
> 'qinfHardwareVersion'   : 2,# Hardware version
> 'qinfFirmwareVersion'   : 3,# Firmware version
> 'qinfCcd'  : 4,# CCD model (see
> QCam_qcCcd)
[ ... ]
 '_qinf_force32'   : 0x
> }

I handled this problem in a kind of cheap, nasty way with (untested)

for k, v in QCam_Info.items():
QCam_Info[v] = k

Then the dictionary lookups work both ways.

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


Re: PEP for module naming conventions

2011-03-17 Thread Mel
Tim Johnson wrote:

> I need to be better informed on naming conventions for modules.  For
> instance, I need to create a new module and I want to make sure that
> the module name will not conflict with any future or current python
> system module names.

COBOL in its golden years had a practice that reserved words were almost 
never hyphenated -- the few that were could be counted on the fingers of 
perhaps four hands and were mostly required paragraph names that were always 
used and hard to forget.

It might turn out well to specify that system module names will never 
contain more than, say, one underscore.  That way, nice descriptive 
application module names like 'analyzer_tool_utils' and such would always be 
safe to use.

Mel.

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


Re: Bounds checking

2011-03-18 Thread Mel
Jean-Michel Pichavant wrote:
> Martin De Kauwe wrote:

> Don't check for bounds, fix any bug in the code that would set your
> values out of bounds and use asserts while debugging.
[ ... ]
> def __setattr__(self, attribute, value):
>if not self.funcTable.get(attribute, lambda x: True)(value):
>sys.exit('error out of bound')
>return object.__setattr(self, attribute, value)

Offhand, my only quibble is that sys.exit is not helpful for debugging.  
Much better to raise an error:

if not self.funcTable.get(attribute, lambda x: True)(value):
raise ValueError ('error out of bound')

or define a subclass of ValueError just for this purpose.  On error, the 
program will stop just as dead, but you'll get a trace.

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


Re: Guido rethinking removal of cmp from sort method

2011-03-24 Thread Mel
Carl Banks wrote:

> On Mar 23, 1:38 pm, Paul Rubin  wrote:
>> Well, I thought it was also to get rid of 3-way cmp in general, in favor
>> of rich comparison.
>
> Supporting both __cmp__ and rich comparison methods of a class does
> add a lot of complexity.  The cmp argument of sort doesn't.
>
> The cmp argument doesn't depend in any way on an object's __cmp__
> method, so getting rid of __cmp__ wasn't any good readon to also get
> rid of the cmp argument; their only relationship is that they're
> spelled the same.  Nor is there any reason why cmp being a useful
> argument of sort should indicate that __cmp__ should be retained in
> classes.

I would have thought that the upper limit of cost of supporting cmp= and
key= would be two different internal front-ends to the internal
internal sort.

Mel.

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


Re: send function keys to a legacy DOS program

2011-03-29 Thread Mel
Alexander Gattin wrote:
> Another thing is that you may need to send key
> release after key press in order for the
> application to trigger the F5/F2/F7 event. I'm not
> sure what the scan codes for F5/F2/F7 releases
> are, but think that they may be:
>
> F5: 0xBF
> F2: 0xBC
> F7: 0xC1

True.  The key-release codes are the key-press codes (the "key numbers")
but with the high-order bit set.

Mel.

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


Re: TypeError: iterable argument required

2011-04-04 Thread Mel
Νικόλαος Κούρας wrote:

>> > iam getting the following error which i dont understand
>>
>> > **
>> > 163         # insert guest comments into database if form was
>> > submitted
>> >   164         if "@" in mail and comment not in ("Σχολιάστε ή ρωτήστε
>> > με σχετικά", ""):
>> >   165                 try:
>> >   166                         cursor.execute( '''INSERT INTO
>> > users(mail, comment) VALUES(%s, %s)''', (mail, comment) )
>> > mail = None, comment = None
>>
>> > TypeError: iterable argument required
>> >       args = ('iterable argument required',)
>>

> In my original question can you explain to me what the meaning of the
> following error is?
>
> 
> mail = None, comment = None
> TypeError: iterable argument required
>   args = ('iterable argument required',)
> *
>
> Also i noticed that if i append a query string in the end of a url
> with the varibble mail attached like
>
> http://superhost.gr/hosting.html?mail=test
>
> then page hosting.html does load without any problem.
>
> If i remove the query string from the ned of the URL then i'am getting
> the error message i posted.
>
> So its not that the if condition is wrong but something happens with
> the form variable 'mail' .

My wild guess is that the trouble is in `if "@" in mail` .  You can only
test somthing `in` something if the second thing is iterable.  So when
you don't supply a value via `?mail=' -- maybe the code that sets the
value of `mail` from the URL (code you don't show us) sets `mail=None`,
your server-side code blows up.  Things would be simpler if you included
a traceback in your error logging.

Mel.

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


Re: is python 3 better than python 2?

2011-04-05 Thread Mel
neil wrote:

> what are the advantages? if it wasn't for python 3 breaking backwards
> compatibility would it be the better choice? 

IMHO the killer app for Python 3 is in more reasonable support for
foreign character sets (no matter where your are, at least one out of
the hundred-odd Unicode character sets is going to be foreign,) and
generally internationalized data processing.

Mel.

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


Re: [OT] Free software versus software idea patents

2011-04-07 Thread Mel
harrismh777 wrote:
> Steven D'Aprano wrote:

>>> >  At this point Microsoft has absolutely nothing to offer the computer
>>> >  science community at large except bzillions of euros ( or dollars ) of
>>> >  wasteful litigation and head-ache.
>> Do you have an example of this wasteful litigation?
>
>  You have to be kidding, right?  Check *any* of the sites I listed 
> above and read about it... software idea patent litigation is a business 
> now worth billions of dollars per year. 

One of the premier sites:

http://www.groklaw.net/

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


Re: Argument of the bool function

2011-04-08 Thread Mel
candide wrote:
> About the standard function bool(), Python's official documentation 
> tells us the following :
>
> bool([x])
> Convert a value to a Boolean, using the standard truth testing procedure.
>
> In this context, what exactly a "value" is referring to ?
>
> For instance,
>  >>> x=42
>  >>> bool(x=5)
> True
>  >>>

Cute.  What's happening here is that `x=5` isn't really an expression. 
It's passing a value to the named parameter `x`, specified in the
definition of `bool`.  Try it with something else:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> bool(y=5)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'y' is an invalid keyword argument for this function



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


Re: Argument of the bool function

2011-04-10 Thread Mel
Chris Angelico wrote:

> Who would use keyword arguments with a function that takes only one arg
> anyway?

It's hard to imagine.  Maybe somebody trying to generalize function calls 
(trying to interpret some other language using a python program?)

# e.g. input winds up having the effect of ..
function = bool
name = 'x'
value = 'the well at the end of the world'
## ...
actions.append ((function, {name:value}))
## ...
for function, args in actions:
results.append (function (**args))

Not something I, for one, do every day.  But regularity in a language is 
good when you can get it, especially for abstract things like that.

I can sort of guess that `dir` was perhaps coded in C for speed and doesn't 
spend time looking for complicated argument lists.

Python is a pragmatic language, so all the rules come pre-broken.


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


Re: Feature suggestion -- return if true

2011-04-12 Thread Mel
Paul Rubin wrote:

> zildjohn01  writes:
>> _temp = expr
>> if _temp: return _temp
> 
> I'm trying to figure out a context where you'd even want that, and I'm
> thinking that maybe it's some version of a repeat-until loop?  Python
> doesn't have repeat-until and it's been proposed a few times.

I can imagine

return? tree_node.left
return? tree_node.right

although my real code would probably be more like

if tree_node.left is not None:
return "left", tree_node.left
if tree_node.right is not None:
return "right", tree_node.right

where adding the "left" and "right" markers makes the return? feature 
impossible to use.

The proposed feature reminds me of the `zod` function (was that the actual 
name?) that returned 0 rather than bringing on a ZeroDivideError.  It would 
cement a strange corner-case into the language.

Mel.

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


Re: List comprehension vs filter()

2011-04-20 Thread Mel
Chris Angelico wrote:
> On Wed, Apr 20, 2011 at 5:16 PM, Tim Roberts  wrote:
>> You can solve this through the common lamba idiom of a closure:
>>
>> lst=filter(lambda x,posttype=posttype: x["type"].lower()==posttype,lst)
> 
> Seems a little odd, but sure. I guess this means that a function's
> default arguments are evaluated in the parent context, but the body is
> evaluated in its own context?

The operation of calling a function has to evaluate arguments provided in 
the caller's namespace and assign them to variables in the called function's 
namespace.  Yes.

Mel.

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


Re: dictionary size changed during iteration

2011-04-20 Thread Mel
Laszlo Nagy wrote:

> Given this iterator:
> 
> class SomeIterableObject(object):
>  
>  
> 
>  def __iter__(self):
>  ukeys = self.updates.keys()
>  for key in ukeys:
>  if self.updates.has_key(key):
>  yield self.updates[key]
>  for rec in self.inserts:
>  yield rec
>  
>  
> 
> How can I get this exception:
> 
> RuntimeError: dictionary changed size during iteration
> 
> 
> It is true that self.updates is being changed during the iteration. But
> I have created the "ukeys" variable solely to prevent this kind of
> error. Here is a proof of correctness:
> 
>>>>  d = {1:1,2:2}
>>>>  k = d.keys()
>>>>  del d[1]
>>>>  k
> [1, 2]
>>>>  k is d.keys()
> False
> 
> So what is wrong with this iterator? Why am I getting this error message?

`ukeys` isn't a different dictionary from `self.updates.keys`  I'ts merely 
another name referring to the same dict object.  I think

ukeys = dict (self.updates.keys)

would do what you want.

Mel.

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


Re: dictionary size changed during iteration

2011-04-20 Thread Mel
Mel wrote:
> Laszlo Nagy wrote:
> `ukeys` isn't a different dictionary from `self.updates.keys`  I'ts merely
> another name referring to the same dict object.  I think
> 
> ukeys = dict (self.updates.keys)
> 
> would do what you want.

Sorry.  Belay that.  Thought I'd had enough coffee.

Mel.

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


Re: learnpython.org - an online interactive Python tutorial

2011-04-22 Thread Mel
harrismh777 wrote:

> Heiko Wundram wrote:
>> The difference between strong typing and weak typing is best described
>> by:
>>
>> Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01)
>> [GCC 4.3.4 20090804 (release) 1] on cygwin
>> Type "help", "copyright", "credits" or "license" for more information.
>>>>> >>>  1+'2'
>> Traceback (most recent call last):
>>File "", line 1, in
>> TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>>> >>>
> 
> Yes. And you have managed to point out a serious flaw in the overall
> logic and consistency of Python, IMHO.
> 
> Strings should auto-type-promote to numbers if appropriate.

"Appropriate" is the problem.  This is why Perl needs two completely 
different kinds of comparison -- one that works as though its operands are 
numbers, and one that works as though they're strings.  Surprises to the 
programmer who picks the wrong one.

Mel.

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


Re: Input() in Python3

2011-04-22 Thread Mel
Westley Martínez wrote:
> On Fri, Apr 22, 2011 at 04:49:19PM +1000, Chris Angelico wrote:

>> U NO. NO NO NO. What if someone enters "os.exit()" as their
>> number? You shouldn't eval() unchecked user input!
>> 
>> Chris Angelico
> 
> Right, there's no way to check you're getting a number, however using:
> 
> a = int(input('enter a number > ')) # use float() for floats
> 
> will raise an exception if it can't convert the string.

But sys.exit() doesn't return a string.  My fave is

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> a = int (input ('enter a number >'))
enter a number >sys.setrecursionlimit(1)
Exception RuntimeError: 'maximum recursion depth exceeded while calling a 
Python object' in  ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a 
Python object' in  ignored
Error in sys.excepthook:
RuntimeError: maximum recursion depth exceeded

Original exception was:
Traceback (most recent call last):
  File "", line 1, in 
RuntimeError: maximum recursion depth exceeded while calling a Python object
>>> int (0)
Exception RuntimeError: 'maximum recursion depth exceeded while calling a 
Python object' in  ignored
Exception RuntimeError: 'maximum recursion depth exceeded while calling a 
Python object' in  ignored
Error in sys.excepthook:
RuntimeError: maximum recursion depth exceeded

Original exception was:
Traceback (most recent call last):
  File "", line 1, in 
RuntimeError: maximum recursion depth exceeded while calling a Python object
>>> 


Mel.

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


Re: Input() in Python3

2011-04-25 Thread Mel
Westley Martínez wrote:

> On Fri, Apr 22, 2011 at 10:08:20AM -0400, Mel wrote:
[ ... ]
>> But sys.exit() doesn't return a string.  My fave is
>> 
>> Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
>> [GCC 4.4.3] on linux2
>> Type "help", "copyright", "credits" or "license" for more information.
>> >>> import sys
>> >>> a = int (input ('enter a number >'))
>> enter a number >sys.setrecursionlimit(1)
>> Exception RuntimeError: 'maximum recursion depth exceeded while calling a
>> Python object' in  ignored
[ ... ]

> What?

I guess sys.setrecursionlimit was meant to be called with a large number.  
Calling it with a small one roadblocks the interpreter.  Luckily, there can 
be just enough room to call setrecursionlimit again with something 
reasonable to get it all back.  Not enough room for `eval 
("sys.setrecursionlimit (2000)`, though.

Mel.

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


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

2011-05-03 Thread Mel
Hans Georg Schaathun wrote:

> On 01 May 2011 08:45:51 GMT, Steven D'Aprano
>wrote:
> :  Python uses a data model of "name binding" and "call by object" (also
> :  known as "call by sharing"). I trust I don't need to define my terms,
> :  but just in case:
> 
> Without having the time to get my hand around exactly what this means:
> Simula has three ways of transmitting arguments, namely transmission
> by name, by value, and by reference.  Is transmission by name the same
> as call by object?  Anyway, I have never seen anyone counting more than
> three ways of doing this ...

To illustrate the neither-fish-nor-fowl nature of Python calls:

mwilson@tecumseth:~$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def identify_call (a_list):
...   a_list[0] = "If you can see this, you don't have call-by-value"
...   a_list = ["If you can see this, you have call-by-reference"]
... 
>>> my_list = [None]
>>> identify_call (my_list)
>>> my_list
["If you can see this, you don't have call-by-value"]



so it's neither call-by-value nor call-by-reference as (e.g.) C or PL/I 
programming would have it (don't know about Simula, so I am off topic, 
actually.)  It's not so wrong to think of Python's parameter handling as 
ordinary assignments from outer namespaces to an inner namespace.

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


Re: Why do directly imported variables behave differently than those attached to imported module?

2011-05-03 Thread Mel
Dun Peal wrote:

> Hi!
> 
> Here's the demonstrating code:
> 
> # module foo.py
> var = 0
> 
> def set():
> global var
> var = 1
> 
> Script using this module:
> 
> import foo
> from foo import *
> 
> print var, foo.var
> set()
> print var, foo.var
> 
> Script output:
> 
> 0 0
> 0 1
> 
> Apparently, the `var` we imported from `foo` never got set, but
> `foo.var` on the imported `foo` - did. Why?

They're different because -- they're different.  `foo.var` is defined in the 
namespace of the foo module.  Introspectively, you would access it as 
`foo.__dict__['var']` .

Plain `var` is in your script's namespace so you could access it as 
`globals()['var']` .  The values given to the vars are immutable integers, 
so assignment works by rebinding.  The two different bindings in 
foo.__dict__ and globals() get bound to different integer objects.

Note too the possible use of `globals()['foo'].__dict__['var'] .  (Hope 
there are no typos in this post.)

Mel.

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


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

2011-05-05 Thread Mel
John Nagle wrote:
> On 5/4/2011 5:46 PM, harrismh777 wrote:
>> Or, as stated earlier, Python should not allow 'is' on immutable objects.
> 
> A reasonable compromise would be that "is" is treated as "==" on
> immutable objects.

I foresee trouble testing among float(5), int(5), Decimal(5) ...

Mel.

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


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

2011-05-05 Thread Mel
Tim Roberts wrote:
> That is not an instance of passing an "int" by reference.  That is an
> instance of passing an "int *" by value.  The fact that the parameter "a"
> in BumpMe happens to be an address is completely irrelevent to the
> definition of the parameter passing mechanism.
> 
> C has pass-by-value, exclusively.  End of story.

Trouble with Turing-complete languages.  If it can be done, you can convince 
a Turing-complete language to do it -- somehow.

PL/I was the converse.  All parameters were passed by reference, so with

some_proc (rocks);

the code in some_proc would be working with the address of rocks.  If you 
wanted pass-by-value you wrote

some_proc ((rocks));

whereupon the compiler would pass in by reference an unnamed temporary 
variable whose value was the expression `(rocks)`.  I suspect the compiler I 
used avoided FORTRAN's troubles the same way.  Your function could corrupt 
*a* 4, but it wouldn't corrupt the *only* 4.

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


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

2011-05-05 Thread Mel
Steven D'Aprano wrote:

> Some day, we'll be using quantum computers without memory addresses, [ ... 
] it will still be possible to
> represent data indirectly via *some* mechanism.

:)  Cool!  Pass-by-coincidence!  And Python 3 already has dibs on the 
'nonlocal' keyword!

Mel.

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


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

2011-05-09 Thread Mel
Steven D'Aprano wrote:

> 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's a way around that too.  Describe literals as "magic names" or 
"Platonic names" that are bound to objects in ideal space.  I actually 
considered that for a while as a way of explaining to newbs why the 
characters in a string literal could be different from the characters in the 
string value.  This would probably have troubles of its own; I never took it 
through the knock-down drag-out disarticulation that would show what the 
problems were.

Mel.

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


Re: Obtaining a full path name from file

2011-05-24 Thread Mel
Tim Golden wrote:

> On 24/05/2011 16:36, RVince wrote:
>> s = "C:\AciiCsv\Gravity_Test_data\A.csv"
>> f = open(s,"r")
>>
>> How do I obtain the full pathname given the File, f? (which should
>> equal "C:\AciiCsv\Gravity_Test_data"). I've tried all sorts of stuff
>> and am just not finding it. Any help greatly appreciated !
> 
> You're going to kick yourself:
> 
> f.name

There's trouble there, though:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open ('xyzzy.txt')
>>> f.name
'xyzzy.txt'
>>> import os
>>> os.getcwd()
'/home/mwilson'
>>> os.chdir('sandbox')
>>> f.name
'xyzzy.txt'


If you open a file and don't get a full path from os.path.abspath right 
away, the name in the file instance can get out-of-date.

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


Re: bug in str.startswith() and str.endswith()

2011-05-26 Thread Mel
Ethan Furman wrote:

> I've tried this in 2.5 - 3.2:
> 
> --> 'this is a test'.startswith('this')
> True
> --> 'this is a test'.startswith('this', None, None)
> Traceback (most recent call last):
>File "", line 1, in 
> TypeError: slice indices must be integers or None or have an __index__
> method
> 
> The 3.2 docs say this:
> 
> str.startswith(prefix[, start[, end]])
> Return True if string starts with the prefix, otherwise return False.
> prefix can also be a tuple of prefixes to look for. With optional start,
> test string beginning at that position. With optional end, stop
> comparing string at that position
> 
> str.endswith(suffix[, start[, end]])
> Return True if the string ends with the specified suffix, otherwise
> return False. suffix can also be a tuple of suffixes to look for. With
> optional start, test beginning at that position. With optional end, stop
> comparing at that position.
> 
> Any reason this is not a bug?

It's a wart at the very least.  The same thing happened in Python2 with 
range and xrange; there seemed no way to explicitly pass "default" 
arguments.

Mel.

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


Re: bug in str.startswith() and str.endswith()

2011-05-27 Thread Mel
Terry Reedy wrote:

> To me, that says pretty clearly that start and end have to be
> 'positions', ie, ints or other index types. So I would say that the
> error message is a bug. I see so reason why one would want to use None
> rather that 0 for start or None rather than nothing for end.

If you're trying to wrap a call to startswith in a function that "looks 
like" startswith, there's no easy way to pass in the information that your 
caller wants the default parameters.  The case I ran into was

def wrapped_range (start, stop=None, span=None):
do_some_things()
result = range (start, stop, span)  # range doesn't(/didn't) accept this
return result
   

Tne answer in that case was to take *args as the parameter to wrapped_range 
and count arguments to distinguish between the different calls to range. 

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


Re: Python's super() considered super!

2011-05-27 Thread Mel
sturlamolden wrote:

> I really don't like the Python 2 syntax of super, as it violates
> the DRY principle: Why do I need to write super(type(self),self)
> when super() will do? Assuming that 'self' will always be named
> 'self' in my code, I tend to patch __builtins__.super like this:
> 
> import sys
> def super():
> self = sys._getframe().f_back.f_locals['self']
> return __builtins__.super(type(self),self)
> 
> This way the nice Python 3.x syntax can be used in Python 2.x.

Python causes trouble by letting the users get at the internals, but things 
like this make it worthwhile.

Mel.

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


Re: scope of function parameters

2011-05-29 Thread Mel
Henry Olders wrote:

> I just spent a considerable amount of time and effort debugging a program.
> The made-up code snippet below illustrates the problem I encountered:
> 
> def main():
> a = ['a list','with','three elements']
> print a
> print fnc1(a)
> print a
> 
> def fnc1(b):
> return fnc2(b)
> 
> def fnc2(c):
> c[1] = 'having'
> return c
> 
> This is the output:
> ['a list', 'with', 'three elements']
> ['a list', 'having', 'three elements']
> ['a list', 'having', 'three elements']
> 
> I had expected the third print statement to give the same output as the
> first, but variable a had been changed by changing variable c in fnc2.
> 
> It seems that in Python, a variable inside a function is global unless
> it's assigned. This rule has apparently been adopted in order to reduce
> clutter by not having to have global declarations all over the place.
> 
> I would have thought that a function parameter would automatically be
> considered local to the function. It doesn't make sense to me to pass a
> global to a function as a parameter.

It doesn't look like a question of local or global.  fnc2 is passed a 
container object and replaces item 1 in that container.  You see the results 
when fnc2 prints the object it knows as `c`, and you see again when main 
prints the object it knows as `a`.  Python doesn't pass parameters by 
handing around copies that can be thought of as local or global.  Python 
passes parameters by binding objects to names in the callee's namespace.  In 
your program the list known as `a` in main is identically the same list as 
the one known as `c` in fnc2, and what happens happens.

Mel.

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


Re: Doctest failing

2011-09-10 Thread Mel
Tigerstyle wrote:

> Hi guys.
> 
> I'm strugglin with some homework stuff and am hoping you can help me
> out here.
> 
> This is the code:
> 
> small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on')
> 
> def book_title(title):
> """ Takes a string and returns a title-case string.
> All words EXCEPT for small words are made title case
> unless the string starts with a preposition, in which
> case the word is correctly capitalized.
> >>> book_title('DIVE Into python')
> 'Dive into Python'
> >>> book_title('the great gatsby')
> 'The Great Gatsby'
> >>> book_title('the WORKS OF AleXANDer dumas')
> 'The Works of Alexander Dumas'
> """
> new_title = []
> title_split = title.strip().lower().split()
> for word in title_split:
> if title_split[0] in small_words:
> new_title.append(word.title())
> elif word in small_words:
> new_title.append(word.lower())
> else:
> new_title.append(word.title())
> return(' '.join(new_title))
> 
> def _test():
> import doctest, refactory
> return doctest.testmod(refactory)
> if __name__ == "__main__":
> _test()
> 
> All tests are failing even though I am getting the correct output on
> the first two tests. And the last test still gives me "Of" instead of
> "of"
> 
> Any help is appreciated.

I don't know about doctest -- I suspect it wants a structured docstring to 
specify the tests -- but this

if title_split[0] in small_words:
new_title.append(word.title())

can't be what you want.

Mel.

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


Re: Context manager with class methods

2011-09-22 Thread Mel
Gavin Panella wrote:

> Hi,
> 
> On Python 2.6 and 3.1 the following code works fine:
> 
> class Foo(object):
> 
> @classmethod
> def __enter__(cls):
> print("__enter__")
> 
> @classmethod
> def __exit__(cls, exc_type, exc_value, traceback):
> print("__exit__")
> 
> with Foo: pass
> 
> However, in 2.7 and 3.2 I get:
> 
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: __exit__
> 
> Is this a regression or a deliberate change? Off the top of my head I
> can't think that this pattern is particularly useful, but it seems
> like something that ought to work.

This seems to work:



class MetaWith (type):
@classmethod
def __enter__(cls):
print("__enter__")

@classmethod
def __exit__(cls, exc_type, exc_value, traceback):
print("__exit__")

class With (object):
__metaclass__ = MetaWith

with With:
pass



Mel.

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


Re: Context manager with class methods

2011-09-22 Thread Mel
Mel wrote:
> This seems to work:
> 
> 
> 
> class MetaWith (type):
> @classmethod
> def __enter__(cls):
> print("__enter__")
> 
> @classmethod
> def __exit__(cls, exc_type, exc_value, traceback):
> print("__exit__")
> 
> class With (object):
> __metaclass__ = MetaWith
> 
> with With:
> pass

It seems to work equally well without the `@classmethod`s

Mel.

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


Re: Generating equally-spaced floats with least rounding error

2011-09-24 Thread Mel
Steven D'Aprano wrote:

> I'm trying to generate a sequence of equally-spaced numbers between a
> lower and upper limit. Given arbitrary limits, what is the best way to
> generate a list of equally spaced floats with the least rounding error for
> each point?
> 
> For example, suppose I want to divide the range 0 to 2.1 into 7 equal
> intervals, then the end-points of each interval are:
> 
> (0.0)---(0.3)---(0.6)---(0.9)---(1.2)---(1.5)---(1.8)---(2.1)
> 
> and I'd like to return the values in the brackets. Using Decimal or
> Fraction is not an option, I must use floats. If the exact value isn't
> representable as a float, I'm okay with returning the nearest possible
> float.
> 
> The width of each interval is:
> 
> width = (2.1 - 0.0)/7
> 
> The relevant points can be calculated in either of two methods:
> 
> #1 add multiples of the width to the starting value, 0.
> 
> #2 subtract multiples of width from the ending value, 2.1.
> 
> (Repeated addition or subtraction should be avoided, as it increases the
> amount of rounding error.)
> 
> Mathematically the two are equivalent, but due to rounding, they may not
> be. Here's a run using Python 3.2:
> 
>>>> [0.0 + i*width for i in range(8)]
> [0.0, 0.3, 0.6, 0.8999, 1.2, 1.5, 1.7998, 2.1]
> 
> The 4th and 7th values have rounding errors, the rest are exact.
> 
> 
>>>> [2.1 - (7-i)*width for i in range(8)]
> [0.0, 0.30027, 0.6001, 0.9001,
> 1.2002, 1.5, 1.8, 2.1]
> 
> The 2nd, 3rd, 4th and 5th values have rounding errors. Note that the 7th
> value is exact here, but not above.
> 
> Is there a way to pick between methods #1 and #2 (or some combination of
> the two) without human intervention so as to minimise the rounding error?
> Or is there some other way to generate equally-spaced floats? My efforts
> at googling have not been helpful.

When I've done this with ints (usually in small embedded systems) I've 
always preferred

low_limit + (total_width * i) / intervals

since it does the rounding on the biggest numbers where proportional error 
will be least, and it's guaranteed to hit the low_limit and high_limit 
exactly (as exactly as they can be represented, anyway.)

Mel.

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


Re: Wrote a new library - Comments and suggestions please!

2011-09-27 Thread Mel
Steven D'Aprano wrote:
> I googled on "SAS PROC FREQ" and found this:
> 
http://support.sas.com/documentation/cdl/en/procstat/63104/HTML/default/procstat_freq_sect006.htm
> 
> All the words are in English, but I have no idea what the function does,
> how you would call it, and what it returns. Would it have been so hard to
> show a couple of examples?

Hmm.  Yeah.  Very much so.  That's the kind of documentation I call "syntax 
happy".  It tells you how to create a well-formed PROC STAT without ever 
saying what would happen if you did, or why you might want that, whatever it 
was, to happen.  I see that kind of documentation way too often.  By 
comparison, even this <https://www.ubersoft.net/comic/hd/2011/09/losing-
sight-big-picture> might seem good.  At least they try.

"Does things to the stuff.  By default, the most recent stuff is done things 
to."

Mel.

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


Re: Usefulness of the "not in" operator

2011-10-08 Thread Mel
Steven D'Aprano wrote:

> candide wrote:
> 
>> So what is the usefulness of the "not in" operator ? Recall what Zen of
>> Python tells
>> 
>> There should be one-- and preferably only one --obvious way to do it.
> 
> And "not in" is the obvious way to do it.
> 
> 
> "If the key is not in the ignition, you won't be able to start the car."
> 
> "If not the key is in the ignition, you won't be able to start the car."
> 
> 
> Who like that second one speaks?

:)  
"If the key is not in the ignition, you will be able to start the car, not."

Mel.

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


RE: Problem with a wx notebook

2011-10-20 Thread Mel
Prasad, Ramit wrote:

> I've created a wx NoteBook in wich I set multiples panels in wich I
> set one or more sizers. But nothing displays in the notebook,
> everything is outside. I've been searching an answer for 2 days ><.
> Can you help me plz ? Here is my code(with only one panel, to sum up
> the code) :
> 
> class StreamingActivationDialog(wx.Dialog):
> def __init__(self, *args, **kwds):
> # begin wxGlade: StreamingActivationDialog.__init__
> kwds["style"] = wx.DEFAULT_DIALOG_STYLE
> wx.Dialog.__init__(self, *args, **kwds)
> self.bitmap_1_copy = wx.StaticBitmap(self, -1, wx.Bitmap("img\
> \logo.png", wx.BITMAP_TYPE_ANY))
> self.labelDnD = wx.StaticText(self, -1, "Si vous avez déjà un
> fichier d'activation, faite le glisser dans cette fenetre")
> self.keyBitmap = wx.StaticBitmap(self, -1, wx.Bitmap("img\
> \key.bmp", wx.BITMAP_TYPE_ANY))
> self.conclude = wx.StaticText(self, -1, _("test"),
> style=wx.ALIGN_CENTRE)
> 
> ### Panel ###
> self.intro3_label = wx.StaticText(self, -1, "Envoyez un mail à
> \nactivat...@monmail.com\ncontenant le code :",style=wx.ALIGN_CENTRE)
> self.activationCode_label= wx.StaticText(self, -1,
> "123456789", style=wx.TE_READONLY)
> self.copy2_Button = wx.Button(self, -1, "Copier dans le presse-
> papier")
> self.copy2_Button.Bind(wx.EVT_BUTTON, PanelMail.onCopy)
> ##
> 
> self.note = wx.Notebook(self, wx.ID_ANY, style=wx.BK_LEFT,
> size=wx.Size(100, 341))
> self.page3 = wx.Panel(self.note)
> 
> imagelist = wx.ImageList(94, 94)
> bitmap1 = wx.Bitmap("img\\a.bmp", wx.BITMAP_TYPE_BMP )
> imagelist.Add(bitmap1)
> self.note.AssignImageList(imagelist)
> 
> self.__set_properties()
> self.__do_layout()
> # end wxGlade
> 
> def __set_properties(self):
> # begin wxGlade: StreamingActivationDialog.__set_properties
> self.SetTitle(_("Activation de FlashProcess"))
> self.SetBackgroundColour(wx.Colour(255, 255, 255))
> #self.linkProblem.SetForegroundColour(wx.Colour(0, 0, 0))
> # end wxGlade
> 
> def __do_layout(self):
> # begin wxGlade: StreamingActivationDialog.__do_layout
> self.grid_sizer_1 = wx.FlexGridSizer(6, 1, 0, 0)
> self.grid_sizer_2 = wx.FlexGridSizer(1, 2, 0, 30)
> self.grid_sizer_1.Add(self.bitmap_1_copy, 0, wx.TOP|wx.BOTTOM|
> wx.EXPAND, 10)
> 
> 
> ### Page 3 ###
> sizer = wx.BoxSizer(wx.VERTICAL)
> sizer.Add(self.intro3_label, 0, wx.BOTTOM|wx.ALIGN_CENTER, 5)
> sizer.Add(self.activationCode_label, 0, wx.BOTTOM|
> wx.ALIGN_CENTER, 20)
> sizer.Add(self.copy2_Button, 0, wx.ALIGN_CENTER, 20)
> 
> self.page3.SetSizer(sizer)
> sizer.Fit(self.page3)
> ##
> 
> self.note.AddPage(self.page3, "", False, 0)
[ ... ]

It looks a though all the controls that are meant for page3 have been 
created with the top-level dialog as their parent.  AFAIK this cannot be.
self.page3 is (correctly) a child window of self.note, but the controls to 
be shown inside have to be children of self.page3 .  Putting things into the 
sizers is not enough.

In my own code, I usually define a separate class descended from wx.Panel to 
create a page3 instance with its own sizers, then create one of those with a 
a wx.Notebook instance as a parent, and add it to the notebook:

def _new_capture_page (self):
new_trace = TraceWindow (self.tracebook)
self.tracebook.AddPage (new_trace, 'Capture %d' %  
(self.capture_serial,), select=True)
return new_trace


Hope this helps,

Mel.


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


Re: How to isolate a constant?

2011-10-25 Thread Mel
Dennis Lee Bieber wrote:

> Where's the line form to split those who'd prefer the first vs the
> second result in this sample :
> 
>>>> unExpected = "What about a string"
>>>> firstToLast = unExpected[:]
>>>> repr(firstToLast)
> "'What about a string'"
>>>> explicitList = list(unExpected)
>>>> repr(explicitList)
> "['W', 'h', 'a', 't', ' ', 'a', 'b', 'o', 'u', 't', ' ', 'a', ' ', 's',
> 't', 'r', 'i', 'n', 'g']"
>>>> 

Well, as things stand, there's a way to get whichever result you need.  The 
`list` constructor builds a single list from a single iterable.  The list 
literal enclosed by `[`, `]` makes a list containing a bunch of items.

Strings being iterable introduces a wrinkle, but `list('abcde')` doesn't 
create `['abcde']` just as `list(1)` doesn't create `[1]`.

Mel.

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


Re: How do I Color a QTableView row in PyQt4

2007-03-02 Thread Mel
Now that I can change the row colors of QTableView when loading data I
now need to be able to set the color of the row at anytime.  I've been
trying by using an item delegate but I'm not sure if I'm using it
correctly.  Would I try and set an item delegate for the row and
change the background color that way?  An example or a link to easy to
understand documentation on changing a row color for an object based
on QTableView using QSqlQueryModel as a model would be greatly
appreciated.  I'm still a bit confused in Qt4.

Mel

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


How do I Color a QTableView row in PyQt4

2007-02-28 Thread Mel
I am currently porting an SQL centered Visual Basic application to run
on Linux, Python, and Qt4.  Currently I am stumped on changing row
colors in the QTableView widget.  My test code is based on code from
the PyQt4  examples and looks like this:

*** Start Code ***

import sys
from PyQt4 import QtCore, QtGui, QtSql

import connection


class CustomSqlModel(QtSql.QSqlQueryModel):
def data(self, index, role):
value = QtSql.QSqlQueryModel.data(self, index, role)
if value.isValid() and role == QtCore.Qt.DisplayRole:
if index.column() == 0:
return QtCore.QVariant(value.toString().prepend("#"))
elif index.column() == 2:
return QtCore.QVariant(value.toString().toUpper())
if role == QtCore.Qt.TextColorRole and index.column() == 1:
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.blue))
return value

def initializeModel(model):
model.setQuery("SELECT * FROM WaterOrder Where DateCanceled is
NULL AND ActDateTimeOff is NULL and ActDateTimeOn is NOT NULL")

offset = 0
views = []

def createView(title, model):
global offset, views

view = QtGui.QTableView()
views.append(view)
view.setModel(model)
view.setWindowTitle(title)
for i in range(model.columnCount()):
view.resizeColumnToContents(i)
view.setAlternatingRowColors(1)

view.move(100 + offset, 100 + offset)
offset += 20
view.show()


if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
if not connection.createConnection():
sys.exit(1)

customModel = CustomSqlModel()
initializeModel(customModel)
createView(QtCore.QObject.tr(customModel, "Running Water"),
customModel)

sys.exit(app.exec_())

*** End Code ***


Column 18 in the table shows a number from 1 to 3.  I would like to
change the color of the row based on the value in column 18 but I have
not been able to find any resources that show me how.  Can anyone lend
a hand?

Thanks,
Mel

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


Re: How do I Color a QTableView row in PyQt4

2007-03-01 Thread Mel
On Feb 28, 5:08 pm, David Boddie <[EMAIL PROTECTED]> wrote:
> On Wednesday 28 February 2007 18:55, Mel wrote:
>
>
>
> > I am currently porting an SQL centered Visual Basic application to run
> > on Linux, Python, and Qt4.  Currently I am stumped on changing row
> > colors in the QTableView widget.  My test code is based on code from
> > the PyQt4  examples and looks like this:
>
> > *** Start Code ***
>
> > import sys
> > from PyQt4 import QtCore, QtGui, QtSql
>
> > import connection
>
> > class CustomSqlModel(QtSql.QSqlQueryModel):
> > def data(self, index, role):
> > value = QtSql.QSqlQueryModel.data(self, index, role)
> > if value.isValid() and role == QtCore.Qt.DisplayRole:
> > if index.column() == 0:
> > return QtCore.QVariant(value.toString().prepend("#"))
> > elif index.column() == 2:
> > return QtCore.QVariant(value.toString().toUpper())
> > if role == QtCore.Qt.TextColorRole and index.column() == 1:
> > return QtCore.QVariant(QtGui.QColor(QtCore.Qt.blue))
> > return value
>
> [Snipping the rest of the code to keep this post short.]
>
> > Column 18 in the table shows a number from 1 to 3.  I would like to
> > change the color of the row based on the value in column 18 but I have
> > not been able to find any resources that show me how.  Can anyone lend
> > a hand?
>
> It's interesting to see that you subclassed QSqlQueryModel instead of
> using a custom delegate to display the data. It's usually recommended
> that you subclass QItemDelegate if you want to customize the way items
> are represented, but you can also customize the model if you want.
>
> What you can do is to check to see if the requested role is the
> Qt.BackgroundRole and, if so, query the base class for the data in
> column 18 in the same row. Then you can supply a different colour
> (as a brush, actually) depending on the value you obtained.
>
> if role == QtCore.Qt.BackgroundRole:
> # Get the data from column 18.
> column18_data = index.sibling(index.row(), 18).data()
> # The data is stored in a QVariant, so we unpack it.
> integer_value = column18_data.toInt()[0] # just the value
> # Look up the associated color in a dictionary which you
> # have already defined, and return it.
> color = self.colors.get(integer_value, self.default_color)
> return QtCore.QVariant(QtGui.QBrush(color))
>
> You might also find the following pages useful:
>
> http://www.riverbankcomputing.com/Docs/PyQt4/html/qt.html#ItemDataRol...http://doc.trolltech.com/4.2/model-view-model.html
>
> Good luck!
>
> David

Thanks David, that did work as I had hoped.  I just need to work on
the colors a bit and make them more appealing.

Here is my final code that works for the custom Sql Model.

class CustomSqlModel(QtSql.QSqlQueryModel):
def data(self, index, role):
value = QtSql.QSqlQueryModel.data(self, index, role)
if value.isValid() and role == QtCore.Qt.DisplayRole:
if index.column() == 0:
return QtCore.QVariant(value.toString().prepend("#"))
elif index.column() == 2:
return QtCore.QVariant(value.toString().toUpper())
if role == QtCore.Qt.TextColorRole and index.column() == 1:
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.blue))
if role == QtCore.Qt.BackgroundRole:

# Get the data from column 18.

column18_data = index.sibling(index.row(), 18).data()

# The data is stored in a QVariant, so we unpack it.

integer_value = column18_data.toInt()[0] # just the value

# Look up the associated color in a dictionary which you

# have already defined, and return it.
if integer_value == 1:

return
QtCore.QVariant(QtGui.QBrush(QtGui.QColor(QtCore.Qt.red)))
if integer_value == 2:

return
QtCore.QVariant(QtGui.QBrush(QtGui.QColor(QtCore.Qt.yellow)))
if integer_value == 3:

return
QtCore.QVariant(QtGui.QBrush(QtGui.QColor(QtCore.Qt.green)))
return value


Mel

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


Re: Recursive loading trouble for immutables

2007-11-25 Thread Mel
rekkufa wrote:
> I am currently building a system for serializing python objects
 > to a readable file-format, as well as creating python objects by
 > parsing the same format. It is more or less complete except for
 > a single issue I just cannot figure out by myself: How to load
 > data that specifies immutables that recursively reference
 > themselves.
> 
> There are only a few solutions I can think of.
> 
> One: While loading recursive objects, I always create empty versions
 > of objects (lists, dicts, classes) etc, and fill them in afterwards.
 > This works fine for loading recursive lists and such, but as
 > immutables are, well, immutable, this gets me nowhere with important
 > datatypes like tuples.
> [ ... ]

I can imagine a C function that might do it.
If it were a list, of course, a Python function would be easy:

def IdioList (contents, marker):
 t = []
 t[:] = [x if x is not marker else t for x in contents]
 return t

With tuples, by the time we have the tuple's identity it's too late,
but I suspect that in C we could bend the rules enough.
The marker would be a caller-supplied object with the property that 
the caller would never want to put it in a self-referencing sequence.

I'll have to check this out today to see.

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


Re: Recursive loading trouble for immutables

2007-11-25 Thread Mel
Mel wrote:
> rekkufa wrote:
[ ... ]
>> How to load
>> data that specifies immutables that recursively reference
>> themselves.
> I can imagine a C function that might do it.
[ ... ]

Here's something that works, in the sense of creating a tuple 
containing a self-reference.  I don't know how dangerous it realliy is 
-- haven't tested for memory leaks or any other large-scale trouble.
Also, I've only tested on Python 2.5.1 under Ubuntu Linux.

Called as

idiotuple.idiotuple (a_sequence, a_marker)

it returns a tuple containing the items of a_sequence, except that 
instances of a_marker are replaced by references to the returned 
tuple.   Eg.:

import idiotuple
class IdioMarker: "An object that I will never insert into a tuple."
def showid (x):
 print id(x)
 for y in x:
 print '  ', id(y)

showid (idiotuple.idiotuple ((1,2,3), IdioMarker))
showid (idiotuple.idiotuple ((1, IdioMarker, 3), IdioMarker))



The C code is:


/* $Id$ */
#include 

/*===*/

static PyObject *idiotuple_idiotuple (PyObject *self, PyObject *args)
// In Python, call with
//sequence contents
//object marker
// returns
//tuple containing contents, with instances of marker
//  replaced by borrowed self-references
{
 PyObject *t = NULL;
 PyObject *contents, *marker, *x;
 Py_ssize_t i, n, z;
 if (!PyArg_ParseTuple (args, "OO", &contents, &marker))
 return NULL;
 n = PySequence_Size (contents);
 if (n < 0)
 return NULL;
 t = PyTuple_New (n);// new tuple
 if (t == NULL)
 return NULL;
 for (i=0; i < n; ++i) {
 x = PySequence_GetItem (contents, i);// new reference
 if (x != marker) {
 z = PyTuple_SetItem (t, i, x);// steals the new 
reference to x
 if (z == -1) {
 goto fail;
 }
 }
 if (x == marker) {
 z = PyTuple_SetItem (t, i, t);// stolen reference to t
 // Dereference the marker.
 // The internal reference to the tuple is effectively 
'borrowed'.
 // Only external references to the tuple are reflected in 
its reference count.
 Py_DECREF (x);// dereference the marker
 if (z == -1) {
 goto fail;
 }
 }
 }
 return t;
fail:
 Py_DECREF (t);// arrange for the tuple to go away
 return NULL;
} /* idiotuple_idiotuple */


/*===*/

static PyMethodDef IdioTupleMethods[] = {
 {"idiotuple", idiotuple_idiotuple, METH_VARARGS, "Create a 
possibly self-referential tuple."},
 {NULL, NULL, (int)NULL, NULL}
};

PyMODINIT_FUNC initidiotuple (void)
{
 PyObject *module;
 module = Py_InitModule ("idiotuple", IdioTupleMethods);
}





Setup.py is


# for use by distutils
from distutils.core import setup, Extension

module1 = Extension('idiotuple',
 sources = ['idiotuple.c'])

setup (name = 'idiotuple',
version = '1.0',
description = 'Create a possibly self-referential tuple.',
author = 'Mel Wilson',
author_email = '[EMAIL PROTECTED]',
ext_modules = [module1])


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


Re: basic if stuff- testing ranges

2007-11-25 Thread Mel
Donn Ingle wrote:
> Sheesh, I've been going spare trying to find how to do this short-hand:
> if 0 > x < 20: print "within"
> 
> So that x must be > 0 and < 20.
> 
> I usually do:
> if x > 0 and x < 20: print "within"
> 
> What's the rule? Does it even exist?

if 0 < x < 20:
 ?


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


Re: Unexpected behavior when initializing class

2007-11-28 Thread Mel
Paul Rudin wrote:
> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> A common paradigm to get round this - assuming you want a different
> empty list each time - is something like:
> 
> def __init__(self, v = None):
> self.values = v if v else []
> 
> (or maybe test explicitly for None, but you get the idea.)

Do test explicitly for None.  Otherwise, if you do

a = []
x = ThatClass (a)


it will so happen that x.values will be an empty list, but it won't be 
the same list as a.

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


Re: [OT] minimalist web server

2007-12-01 Thread Mel
Daniel Fetchinson wrote:
> Maybe I found what I'm looking for: cheetah, a web server that is 600
> lines of C code and that's it :)
> 
> http://freshmeat.net/projects/cheetahd/

For the sake of on-topicness, there is this:



#!/usr/bin/env python
# -*- coding: ASCII -*-
'''$Id$
'''
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleRequestHandler

handler = HTTPServer (('', 8000), SimpleRequestHandler)
handler.handle_forever()



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


Re: String formatting with %s

2007-12-02 Thread Mel
Donn Ingle wrote:
  > Now, is there something quick like:
>>>> s = "%s/2 and %s/1" % ( "A", "B" )
>>>> print s
> B and A
> 
> ?

GNU glibc printf accepts a format string:

printf ("%2$s and %1$s", "A", "B");

to produce what you want -- but not Python, AFAIK.


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


Re: Escaping the semicolon?

2007-12-04 Thread Mel
Nick wrote:
> Is this expected behavior?
> 
>>>> s = '123;abc'
>>>> s.replace(';', '\;')
> '123\\;abc'
> 
> I just wanted a single backslash. I can see why this probably happens
> but i wondered if it is definitely intentional.

What you're seeing on the screen is a "literalization" of the string 
value for the sake of the display.  Consider

Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> s = '123;abc'
 >>> b = s.replace(';', '\;')
 >>> b
'123\\;abc'
 >>> len(b)
8


The length suggests that there's only one backslash in the string.


Mel.

On the other hand

 >>> repr(b)
"'123;abc'"

Isn't what I expected.  No, wait, it is.  It's the value of repr(b) 
repred by the Python display logic.

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


Re: About Rational Number (PEP 239/PEP 240)

2007-12-16 Thread Mel
Steven D'Aprano wrote:

> Yes, but my point (badly put, I admit) was that people find fractions far 
> easier to work with than they find floating point numbers. 

I'm not so sure.  I got caught by the comic XKCD's 
infinite-resistor-grid thing, and simplified it to a ladder network -- 
call it L -- made up of 2 1-ohm resistors in series with a 1-ohm 
resistor paralleled by L.  Simulating this -- assuming an arbitrary 
endpoint with resistance 3 -- well, it takes a little thought to 
decide that 11/15 < 3/4, and a lot more to decide the same thing for 
153/209 and thus decide whether the series is coming or going.

Then when you work out the right answer from

L = 2 + (L / (L+1))

that answer depends on sqrt(12), which Rationals handle just as badly 
as floats, and at far greater expense.

I wrote a Rational class back when I was learning to do these things 
in Python, and it was actually pretty easy: a dash of GCD, a pinch of 
partial fractions, and a lot of following the Python Reference Manual. 
It eventually worked as advertised, but I haven't used it since. 
It could stand to be updated to use the __new__ method and produce 
genuinely immutable instances, if I could find the source.

Mel.
And with any
> rational data type worth the name, you simply should never get anything 
> as unintuitive as this:
> 
>>>> from __future__ import division
>>>> 4/10 + 2/10 == 6/10
> False
> 
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List problem

2007-12-16 Thread Mel
Alan Bromborsky wrote:
> I wish to create a list of empty lists and then put something in one of 
> the empty lists.  Below is what I tried, but instead of appending 1 to 
> a[2] it was appended to all the sub-lists in a.  What am I doing wrong?
> 
> a = 6*[[]]
>  >>> a
> [[], [], [], [], [], []]
>  >>> a[2].append(1)
>  >>> a
> [[1], [1], [1], [1], [1], [1]]
>  >>> 

What you've done is equivalent to

x = []
a = [x, x, x, x, x, x]
del x

An idiom for what you want is

a = [[] for y in xrange (6)]

which will populate a with 6 distinct empty lists.

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


Re: exception message output problem

2007-12-22 Thread Mel
Lie wrote:
> PPS: Actually, what makes a tuple is both the parens and the comma,
> with comma as the minimum signifier, inspect this: "str(a) +
> str((a,b,c))", you have to use the double parens, one to make the
> tuple and the other as part of the str. This harmless little case
> gives error if done without the double parens, but what would happen
> if we exchange the str into a function that accepts one argument and
> several optional arguments (or better yet, one argument and an
> optional * argument)?

I think the effect there is operator precedence.  In

str(a,b,c)

the function-calling operator () takes over, and the commas are 
considered as argument separators.  In

str ((a,b,c))

the inner parens present a single tuple-expression to the 
function-calling operator.

Just like  a+b/c  as against  (a+b)/c  but with esoteric overloading 
of ( ) and , .


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


Re: __init__ explanation please

2008-01-14 Thread Mel
Hrvoje Niksic wrote:
> Wildemar Wildenburger <[EMAIL PROTECTED]> writes:
> 
>> Jeroen Ruigrok van der Werven wrote:
>>> To restate it more correctly: __init__ is akin to a constructor.
>>>
>> No. See Hrvoje Niksic's reply (and Ben Finney's to which it was a
>> reply).
>>
>> __init__() /initializes/ an instance (automatically after
>> creation). It is called, /after/ the instance has been constructed
> 
> I don't understand the purpose of this "correction".  After all,
> __init__ *is* the closest equivalent to what other languages would
> call a constructor.  

Nevertheless, __init__ doesn't construct anything.  You can even call 
it to reinitialize an existing object:


Python 2.5.1 (r251:54863, May  2 2007, 16:56:35)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> class AClass (object):
...   def __init__ (self):
... self.a = 4
...
 >>> a = AClass()
 >>> a.a
4
 >>> a.a = 5
 >>> a.a
5
 >>> a.__init__()
 >>> a.a
4



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


Re: no pass-values calling?

2008-01-16 Thread Mel
J. Peng wrote:

> Sounds strange.
> In perl we can modify the variable's value like this way:
> 
> $ perl -le '
>> $x=123;
>> sub test {
>> $x=456;
>> }
>> test;
>> print $x '
> 456

Not all that strange.  The Python equivalent is

x=123
sub test()
 global x
 x=456
test()
print x

Python assignment works by binding an object with a name in a 
namespace.  I suspect that perl does something similar, and the 
differences are in the rules about which namespace to use.

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


Re: assigning values in python and perl

2008-01-16 Thread Mel
J. Peng wrote:
> May I ask, python's pass-by-reference is passing the object's
> reference to functions, but perl, or C's pass-by-reference is passing
> the variable itself's reference to functions. So althought they're all
> called pass-by-reference,but will get different results.Is it?
> 
> On Jan 17, 2008 11:34 AM, J. Peng <[EMAIL PROTECTED]> wrote:
>> I just thought python's way of assigning value to a variable is really
>> different to other language like C,perl. :)
>>
>> Below two ways (python and perl) are called "pass by reference", but
>> they get different results.
>> Yes I'm reading 'Core python programming', I know what happened, but
>> just a little confused about it.
>>
>> $ cat t1.py
>> def test(x):
>> x = [4,5,6]
>>
>> a=[1,2,3]
>> test(a)
>> print a

As I said somewhere else, it's all about binding to names in namespaces.

a=[1,2,3]

creates a list and binds it with the name 'a' in the current namespace.

test(a) (along with def test(x)) takes the object named 'a' in the 
current namespace and binds it with the name 'x' in function test's 
local namespace.  So, inside test, the name 'x' starts by referring to 
   the list that contains [1,2,3].  But the only use test makes of the 
name 'x' is to re-bind it to a new list [4,5,6].  Exiting test, the 
local namespace is thrown away.

You could change your program a bit to clarify what's going on:

def test(x):
 print "x=", x
 x = [4,5,6]
 print "x=", x
a=[1,2,3]
test(a)
print "a=", a


Cheers, Mel


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


Re: "Code Friendly" Blog?

2008-01-17 Thread Mel
Hai Vu wrote:
> On Jan 17, 2:50 pm, Miki <[EMAIL PROTECTED]> wrote:
>> Hello,
>>
>> Posting code examples to blogger.com hosted blog is not fun (need to
>> remember alway escape < and >).
>> Is there any free blog hosting that is more "code friendly" (easy to
>> post code snippets and such)?
>>
>> Thanks,
>> --
>> Miki <[EMAIL PROTECTED]>http://pythonwise.blogspot.com
> 
> how about bracketing your code in the  tags?
> 
> Something like this:
> 
> import sys, os, shutil
> 
> def getDir(fullPath):
> dirName, fileName = os.path.split(fullPath)
> return dirName
> 

That won't help the escape problem, though it will preserve vital 
Python whitespace.  HTML has to be interpreting '<' characters to 
recognize the ''.

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


Re: Just for fun: Countdown numbers game solver

2008-01-20 Thread Mel
[EMAIL PROTECTED] wrote:
> Ever since I learnt to program I've always loved writing solvers for
> the Countdown numbers game problem in different languages, and so now
> I'm wondering what the most elegant solution in Python is.
> 
> If you don't know the game, it's simple: you're given six randomly
> chosen positive integers, and a target (another randomly chosen
> positive integer), and you have to make the target using only the
> numbers you're given, and +,-,* and / (and any number of brackets you
> like). You're not allowed fractions as intermediate values. So, given
> 2, 3 and 5 say, and a target of 21, you could do (2+5)*3 = 21.
> 
> So what's the best algorithm? And, what's the most elegant way to code
> it in Python? I've posted my most elegant version below (I have a
> faster version which is slightly less elegant). Can anyone do better?

I found that postfix notation made it easy to run up all the possible 
expressions based on permutations of the available numbers.  Don't 
know where my source code is ... have to look.

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


Re: problem with 'global'

2008-01-20 Thread Mel
oyster wrote:
> why the following 2 prg give different results? a.py is ok, but b.py
> is 'undefiend a'
> I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC
> v.1310 32 bit (Intel)] on win32
> #a.py
> def run():
> if 1==2:# note, it always False
> global a
> a=1
> 
> run()
> a
> 
> #b.py
> def run():
> a=1
> 
> run()
> a

The docs seem to be in <http://www.python.org/doc/2.4/ref/global.html> 
but don't look all that helpful.  Probably the key is that global is 
not an executable statement, and isn't affected by being subordinate 
to an if statement.  In a.py the function has been primed to define a 
in the global namespace.  In b.py, not.

Docs do describe global as a "directive to the parser", even though 
it's lumped in with normal statements like print, return, yield, 
raise, etc.

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


Re: problem with 'global'

2008-01-21 Thread Mel
Duncan Booth wrote:
> Mel <[EMAIL PROTECTED]> wrote:
> 
>> oyster wrote:
>>> why the following 2 prg give different results? a.py is ok, but b.py
>>> is 'undefiend a'
>>> I am using Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC
>>> v.1310 32 bit (Intel)] on win32
>>> #a.py
>>> def run():
>>> if 1==2:# note, it always False
>>> global a
>>> a=1
>>>
>>> run()
>>> a
>>>
>>> #b.py
>>> def run():
>>> a=1
>>>
>>> run()
>>> a
>> The docs seem to be in <http://www.python.org/doc/2.4/ref/global.html> 
>> but don't look all that helpful.
> 
> Why are you reading Python 2.4 docs? Try 
> http://docs.python.org/ref/global.html
> 
> The first sentence (which hasn't changed since 2.4) describing the global 
> statement seems clear enough to me: "The global statement is a declaration 
> which holds for the entire current code block."

I don't think that would stop the OP from thinking the global 
statement had to be executed.  In the code example, it seems to have 
been stuck in a

 if 1==2: global a

and it still worked.



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


Re: read files

2008-01-21 Thread Mel
J. Peng wrote:
> first I know this is the correct method to read and print a file:
> 
> fd = open("/etc/sysctl.conf")
> done=0
> while not done:
> line = fd.readline()
> if line == '':
> done = 1
> else:
> print line,
> 
> fd.close()
> 
> 
> I dont like that flag of "done",then I tried to re-write it as:
> 
> fd = open("/etc/sysctl.conf")
> while line = fd.readline():
> print line,
> fd.close()
> 
> 
> this can't work.why?

Formally, because line = fd.readline() is a statement, not an
expression, and it can't be put into an if statement like that.

The most idiomatic way is probably


fd = open ("/etc/sysctl.conf")
for line in fd:
print line



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


Re: refcount

2008-01-29 Thread Mel
Benjamin wrote:
> On Jan 29, 5:46 am, Christian Heimes <[EMAIL PROTECTED]> wrote:
>> Simon Pickles wrote:
>>> Hi,
>>> Is is possible to access the refcount for an object?
>>> Ideally, I am looking to see if I have a refcount of 1 before calling del
>> Help on built-in function getrefcount in module sys:
>>
>> getrefcount(...)
>> getrefcount(object) -> integer
>>
>> Return the reference count of object.  The count returned is generally
>> one higher than you might expect, because it includes the (temporary)
>> reference as an argument to getrefcount().
> Are there any cases when it wouldn't?

Well, as long as the object is named "object" in sys.getrefcount's 
namespace, there's at least that one reference to it...

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


Re: extending Python - passing nested lists

2008-01-29 Thread Mel
Christian Meesters wrote:
>> You didn't mention speed in your original post.
> Sorry, perhaps I considered this self-evident - which it is, of course, not.
> 
>> What about using 
>> array.array?  Unless I am mistaken, these are just a thin wrapper
>> around normal C arrays.
> The algorithm I want to implement requires several million floating point
> operations. Neither the array-modules nor numpy's thin layer seem thin
> enough for me. ;-)
> 
>> Anyway you could always convert your list 
>> into a c array, do lots and lots of fast calculations, then convert it
>> back again to a list.
> I guess I am too blind to see, but I couldn't discover a method description
> like "double* PyList_toDouble". So, yes, my question is a C-API-newbie
> question: What is the way to say "myCarray = SomePyMethod(InputPyList)"? Or
> better, what should be here instead
> static PyObject *_foo(PyObject *self, PyObject *args) {
>   double *v;
>   if (!PyArg_Parse(args, "(d)", &v))
> return NULL;
> to get a list as an array of doubles into 'v' (and back to Python)?
> 
> I did read the API-description, but still am lost at this point. I presume,
> once I get to know the answer I'll bang my head on the table ... ;-)

I haven't strictly tried this, but PyArg_ParseTuple and Py_BuildValue 
seem to be the orthodox ways to do Python->C and C->Python conversions.
But if Numpy isn't fast enough, then any Python at all in the solution 
might be too much.  Perhaps keeping your values in a file and reading 
them into the C programs will work.

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


Re: Is it explicitly specified?

2008-02-03 Thread Mel
Steve Holden wrote:
> Diez B. Roggisch wrote:
>> Bjoern Schliessmann schrieb:
>>> mario ruggier wrote:
>>>
>>>> It may sometimes be useful to make use of the conceptual
>>>> difference between these two cases, that is that in one case the
>>>> user did not specify any key and in the other the user explicitly
>>>> specified the key to be None.
>>> Do you have an example where this might be useful?
>>
>> Any situation in which there would otherwise lots of documentation 
>> needed to inform the user that the sentinel value is something else 
>> than None.
>>
>> Take something like this as an example:
>>
>> def update_user(some, values, nullable_value=sentinel):
>>  # first, work with some and values
>>  ...
>>  # then, on something actually being passed to nullable_value
>>  if nullable_value is not sentinel:
>> connection.cursor().execute("update table set value = ?", 
>> nullable_value)
>>
>>
>>
>> I've seen this before, in code from e.g. Alex Martelli.
>>
> Sure, but the OP's question was "Is there any way to tell between 
> whether a keyword arg has been explicitly specified (to the same value 
> as the default for it)". We've drifted a long way from that, since the 
> code you demonstrate doesn't detect an explicit call with 
> nullable_value==sentinel -- the reason being, I submit, that there is no 
> use case for such code.

The code above works on the assumption that the value named sentinel 
is completely out-of-band, and no user has any reason to use the 
sentinel object in a call.  An example up-thread uses a 
uniquely-constructed instance of object for this.  I kind of like 
defining a class, because I get a docstring to explain what's going on.

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


Re: type, object hierarchy?

2008-02-04 Thread Mel
7stud wrote:
> On Feb 3, 10:28 pm, 7stud <[EMAIL PROTECTED]> wrote:
>> From the docs:
>>
>> issubclass(class, classinfo)
>> Return true if class is a subclass (direct or indirect) of classinfo.
> 
> 
> print issubclass(Dog, object)  #True
> print issubclass(type, object)  #True
> print issubclass(Dog, type)   #False
Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> issubclass (object, type)
False
 >>> isinstance (object, type)
True

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


Re: Globals or objects?

2008-02-21 Thread Mel
James Newton wrote:
> Duncan Booth wrote:
>> The easiest way in Python to implement a singleton is just to
>> use a module: all modules are singletons and there is a
>> defined mechanism (import) for accessing them.
[ ... ]
> Could you give a bare-bones demonstration of it that the relative newbie
> that I am can understand?

I had a club-membership application that ran for several years. 
Default pathnames, etc. for the particular year came from a module 
called thisyear.py:
#=


'''Values used to access this years trakkers files.
$Id: thisyear.py,v 1.2 2006/08/26 16:30:23 mwilson Exp $
'''

memberpath = '2006-7/20062007.txt' # path to this years membership CSV
dirname = '2006-7' # directory name for this year


#=
Programs that needed to use the comma-separated-value membership base 
would import thisyear, and pass thisyear.memberpath when creating the 
CSV reader object.  Etc.



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


Re: How about adding rational fraction to Python?

2008-02-24 Thread Mel
Mensanator wrote:
> On Feb 24, 1:09�pm, Lie <[EMAIL PROTECTED]> wrote:
>> I decided to keep the num/den limit low (10) because higher values
>> might obscure the fact that it do have limits. [ ... ]
> 
> Out of curiosity, of what use is denominator limits?
> 
> The problems where I've had to use rationals have
> never afforded me such luxury, so I don't see what
> your point is.

In calculations dealing only with selected units of measure: dollars 
and cents, pounds, ounces and tons, teaspoons, gallons, beer bottles 
28 to a case, then the denominators would settle out pretty quickly.

In general mathematics, not.

I think that might be the point.

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

Re: float / rounding question

2008-02-25 Thread Mel
[EMAIL PROTECTED] wrote:
> Hi I'm very much a beginner with Python.
> I want to write a function to convert celcius to fahrenheit like this
> one:
> 
> def celciusToFahrenheit(tc):
> tf = (9/5)*tc+32
> return tf
> 
> I want the answer correct to one decimal place, so
> celciusToFahrenheit(12) would return 53.6.
> 
> Of course the function above returns 53.601.
> 
> How do I format it correctly?

print celcisuToFahrenheit (12)

will do fine.


Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> def celciusToFahrenheit(tc):
... tf = (float(9)/5)*tc+32
... return tf
...
 >>> celciusToFahrenheit (12)
53.601
 >>> print celciusToFahrenheit (12)
53.6


The straight value display from the interpreter pursues precision to 
the bitter end, doing its formatting with the repr function.  print 
uses str formatting for a more expected result.

Mel.

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


Re: Web site for comparing languages syntax

2008-02-25 Thread Mel
Sebastian Bassi wrote:
> I know there is one site with wikimedia software installed, that is
> made for comparing the syntax of several computer languages (Python
> included). But don't remember the URL. Anyone knows this site?

http://99-bottles-of-beer.net/

is one such site, though I don't know about wikimedia.

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


Re: sqlite3 adaptors mystery

2008-03-01 Thread Mel
Matej Cepl wrote:
[ ... ]
> However, when running this program it seems converter doesn’t seem to work,
> because I get:
> 
> [EMAIL PROTECTED] dumpBugzilla]$ rm test.db ; python testAdaptors.py
> [(u'False',), (u'True',)]
> [EMAIL PROTECTED] dumpBugzilla]$
> 
> There is probably something quite obvious what I do incorrectly, but I just
> don't see it. Could somebody kick me in the right direction, please?

There's nothing much wrong.  cur.fetchall is returning a list of all 
the selected rows, and each row is a tuple of fields.  Each tuple is 
being converted for display by repr, so the strings are shown as 
unicode, which is what they are internally.  Change the print to

for (field,) in cur.fetchall():
 print field

and you'll see your plain-text strings.

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

Re: sqlite3 adaptors mystery

2008-03-02 Thread Mel
Matej Cepl wrote:
> Thanks for your help, but plain-text strings is not what 
> I wanted. The boolean variables was what I was after. See this 
> modified version of the script:
> 
> #!/usr/bin/python
> import sqlite3
> def adapt_boolean(bol):
>  if bol:
>  return "True"
>  else:
>  return "False"
>  
> def convert_boolean(bolStr):
>  if str(bolStr) == "True":
>  return bool(True)
>  elif str(bolStr) == "False":
>  return bool(False)
>  else:
>  raise ValueError, "Unknown value of bool attribute 
> '%s'" % bolStr
>  
> sqlite3.register_adapter(bool,adapt_boolean)
> sqlite3.register_converter("boolean",convert_boolean)
> 
> db = sqlite3.connect(":memory:")
> cur=db.cursor()
> cur.execute("create table test(p boolean)")
> p=False
> cur.execute("insert into test(p) values (?)", (p,))
> p=True
> cur.execute("insert into test(p) values (?)", (p,))
> cur.execute("select p from test")
> for (field,) in cur.fetchall():
> print field,type(field)
> 
> The output here is:
> 
> [EMAIL PROTECTED] dumpBugzilla]$ python testAdaptors.py False  'unicode'>
> True 
> [EMAIL PROTECTED] dumpBugzilla]$ 
> 
> I thought that converter is there for just exactly this -- that 
> I would get back bool values not strings.
> 
> Sorry for not being clear in the first run.

Sorry about the misunderstanding.  It seems you want

db = sqlite3.connect("test.db", detect_types=sqlite3.PARSE_DECLTYPES)

After this, the print shows

False 
True 


Mel.

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


Re: What c.l.py's opinions about Soft Exception?

2008-03-09 Thread Mel
Lie wrote:
[ ... ]
> Soft Exception
> What is "Soft Exception"?
> Soft Exception is an exception that if is unhandled, pass silently as
> if nothing happened. For example, if a variable turns into NoneType,
> it'll raise Soft Exception that it have become NoneException,
> programmers that wants to handle it can handle it with a try...except
> block while programmers that doesn't care about it (or know it won't
> be a problem to his code) can just leave the code as it is.
> 
> Soft Exception differs from Hard Exceptions (the regular Exception) in
> a way that Hard Exception must be handled at all cost or the program
> will be terminated while Soft Exception allow programmers not to
> handle it if they don't want to.
[ ... ]
> Ideology Base:
> - EAAP: Easier to apologize than to ask permission.

Sort of like a COME FROM statement.  Drastic effects on program 
execution: a `raise SoftException` in the middle of a loop would break 
the loop if a catcher existed, or leave the loop running if not.  It 
would really need the ability to resume after catching an exception. 
You can't really talk about 'apologize' around something that's so 
irreparable.

I'd try for this effect by creating a class of objects with 
well-defined callbacks.

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


Re: List Combinations

2008-03-12 Thread Mel
Gerdus van Zyl wrote:
> I have a list that looks like this:
> [['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']]
> 
> how can I get all the combinations thereof that looks like as follows:
> 3,9,5,4,2
> 3,1,5,4,2
> 3,9,5,4,5
> 3,1,5,4,5
> etc.
> 
> Thank You,
> Gerdus

What they said, or, if you want to see it done:


def combi (s):
 if s:
 for a in s[0]:
 for b in combi (s[1:]):
 yield [a] + b
 else:
 yield []

for y in combi ([['3'], ['9', '1'], ['5'], ['4'], ['2', '5', '8']]):
 print y
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getattr(foo, 'foobar') not the same as foo.foobar?

2008-03-13 Thread Mel
Diez B. Roggisch wrote:
>> My understanding is that foo.bar does *not* create a new object.
> 
> Your understanding is not correct.
> 
>>  All it
>> does is return the value of the bar attribute of object foo.  What new
>> object is being created?
> 
> A bound method. This happens through the descriptor-protocol. Please see 
> this example:
> 
> 
> class Foo(object):
> def bar(self):
> pass
> 
> 
> f = Foo()
> a = Foo.bar
> b = f.bar
> c = f.bar
> 
> print a, b, c
> print id(b), id(c)

(What Diez said.)  From what I've seen, f.bar creates a bound method 
object by taking the unbound method Foo.bar and binding its first 
parameter with f.  This is a run-time operation because it's easy to 
re-assign some other function to the name Foo.bar, and if you do, the 
behaviour of f.bar() will change accordingly.

You can get some very useful effects from these kinds of games.  You 
can make f into a file-like object, for example, with

import sys
f.write = sys.stdout.write

Here, f.write *is* a straight attribute of f, although it's a built-in 
method of the file class.  It's still bound, in a way, to sys.stdout. 
  I'm assuming that a different example could create an attribute of f 
that's a bound method of some other object entirely.  I've verified 
that f.write('howdy') prints 'howdy' on standard output.

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


  1   2   3   4   >