Thursday, February 18, 2010

comp.lang.python - 25 new messages in 13 topics - digest

comp.lang.python
http://groups.google.com/group/comp.lang.python?hl=en

comp.lang.python@googlegroups.com

Today's topics:

* Mesothelioma : Dangerous Malignant Cancer That Everyone Should Know It - 1
messages, 1 author
http://groups.google.com/group/comp.lang.python/t/53c01b1b5bdcebed?hl=en
* Static method - 5 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/68f5cd03927c9d3f?hl=en
* Creating Import Hooks - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/9e34f976914880f3?hl=en
* Help with lambda - 5 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/c11c0f7edbed2078?hl=en
* Using class attributes - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/9bd1d65c8f8625ec?hl=en
* DO YOU WANT TO BUY A CELL PHONE? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/6595e1a364b80ee9?hl=en
* Referring to class methods in class attributes - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/bd71264b6022765c?hl=en
* NOW Watch Hot Sexy Star Aishwarya rai <NUDE> Bathing Videos In All Angles. -
1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/b09c5f3a101eb90f?hl=en
* Python 3.0 usage? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/fc5f97fcb89e5474?hl=en
* How to efficiently extract information from structured text file - 1
messages, 1 author
http://groups.google.com/group/comp.lang.python/t/bc8840f8a254056b?hl=en
* Interesting talk on Python vs. Ruby and how he would like Python to have
just a bit more syntactic flexibility. - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/9a88c79d4043ba30?hl=en
* NOW Watch Hot Sexy Star Aishwarya rai Bathing Videos In All Angles. - 1
messages, 1 author
http://groups.google.com/group/comp.lang.python/t/daa1fed2a9f2aa91?hl=en
* unit testing a routine that sends mail - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/33e5d23bbb8724a3?hl=en

==============================================================================
TOPIC: Mesothelioma : Dangerous Malignant Cancer That Everyone Should Know It
http://groups.google.com/group/comp.lang.python/t/53c01b1b5bdcebed?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Feb 18 2010 3:36 am
From: gunman


Mesothelioma : Dangerous Malignant Cancer That Everyone Should Know It

A Dangerous Cancer that darken many great people lives who worked with
asbestos ,

check all of the details about mesothelima secrets at

http://mesotheliomabyasbestos.blogspot.com/2010/02/mesothelioma-malignant-cancer-overview.html

Contents :

Mesothelioma Overview
Mesothelioma Symptoms
Mesothelioma Screening
Mesothelioma Staging
Mesothelioma Dark Day

==============================================================================
TOPIC: Static method
http://groups.google.com/group/comp.lang.python/t/68f5cd03927c9d3f?hl=en
==============================================================================

== 1 of 5 ==
Date: Thurs, Feb 18 2010 3:54 am
From: Bruno Desthuilliers


mk a �crit :

> I'm trying to get print_internal_date become a static method AND to
> refer to it in a class attribute 'tagdata' dict.
>
> class PYFileInfo(FileInfo):
> 'python file properties'
>
> @staticmethod
> def print_internal_date(filename):
> f = open(filename + 'c', "rb")
> data = f.read(8)
> mtime = struct.unpack("<i", data[4:])
> return time.asctime(time.gmtime(mtime[0]))
>
> tagdata = {'compiled_fname': lambda x: x + 'c',
> 'size': os.path.getsize,
> 'internal_date': print_internal_date
> }
(snip)

> def __get_props(self, value):
> py_compile.compile(value)
> for tag, fun in PYFileInfo.tagdata.items():
> self[tag] = fun(value)
>
> But:
>
> c:/Python26/pythonw.exe -u "C:/mp3i/finfo2.py"
> Traceback (most recent call last):
(snip)
> File "C:/mp3i/finfo2.py", line 79, in __get_props
> self[tag] = fun(value)
> TypeError: 'staticmethod' object is not callable
>
>
> I think I know where the problem is: what resides in tagdata is a static
> method 'wrapper', not the function itself, according to:

Indeed. Sorry, I'm afraid I gave you bad advice wrt/ using a
staticmethod here - I should know better :( (well, OTHO staticmethods
are not something I use that often).

Anyway: here are a simplified version of your problem, a possible
solution that _won't_ statisfy your other constraints, 2 ugly hacks that
could work but that I don't really like, and what's possibly the "less
worse" solution if you really need a staticmethod here.

###
class Foo1(object):
""" simplified version of mk's code - test() fails """
@staticmethod
def bar(baaz):
print baaz

tagada = {'bar': bar}

def test(self, baaz):
self.tagada['bar'](baaz)


class Foo2(object):
""" naive solution : kinda work, BUT will fail
with the real code that has plain functions
in 'tagada'
"""
@staticmethod
def bar(baaz):
print baaz

tagada = {'bar': bar}

def test(self, baaz):
self.tagada['bar'].__get__(self)(baaz)


class Foo3(object):
""" working solution 1 : defer the wrapping
of 'bar' as a staticmethod
"""
def bar(baaz):
print baaz

tagada = {'bar': bar}

bar = staticmethod(bar)

def test(self, baaz):
self.tagada['bar'](baaz)


class Foo4(object):
""" working solution 2 : use a lambda """
@staticmethod
def bar(baaz):
print baaz

tagada = {'bar': lambda x : Foo4.bar(x)}

def test(self, baaz):
self.tagada['bar'](baaz)


""" and as a "less worse" solution """

def foo5bar(baaz):
print baaz

class Foo5(object):
tagada = {'bar': foo5bar}

bar = staticmethod(foo5bar)

def test(self, baaz):
self.tagada['bar'](baaz)


###

Another "solution" might be to write an alternate callable
implementation of 'staticmethod' - which I'll leave as an exercise to
the reader (...) - but that's possibly a bit overkill !-)


> http://docs.python.org/reference/datamodel.html
>
> So, how do I get out the wrapped function out of static method without
> class call or instance call? (to be called in self[tag] = fun(value))

cf above. None of the solutions I could came with really statisfy me,
but well, at least 3 of them might be "good enough" depending on the
context. As far as I'm concerned, I'd first try the last one, but YMMV

> Yes, I do know that if I just get rid of @staticmethod, this works
> without a hitch.

But then you can't use print_internal_date as a method !-)

HTH


== 2 of 5 ==
Date: Thurs, Feb 18 2010 4:42 am
From: mk


Bruno Desthuilliers wrote:
>> I think I know where the problem is: what resides in tagdata is a
>> static method 'wrapper', not the function itself, according to:
>
> Indeed. Sorry, I'm afraid I gave you bad advice wrt/ using a
> staticmethod here - I should know better :( (well, OTHO staticmethods
> are not something I use that often).

Do not worry the least bit! I'm testdriving on a closed circuit here for
sake of becoming better 'driver', I'm not going to drive like this on
the streets.

> class Foo2(object):
> """ naive solution : kinda work, BUT will fail
> with the real code that has plain functions
> in 'tagada'
> """
> @staticmethod
> def bar(baaz):
> print baaz
>
> tagada = {'bar': bar}
>
> def test(self, baaz):
> self.tagada['bar'].__get__(self)(baaz)

Well I could always do:

if isinstance(self.tagada['bar'], staticmethod):
self.tagada['bar'].__get__(self)(baaz)
else:
self.tagada['bar'](baaz)

But 1. this apparently defeats the purpose of using print_internal_date
on instance/class in 'normal' way, and 2. I probably shouldn't be doing
that since using isinstance is apparently like playing with yourself:
while technically legal, people look at you weirdly. :-)

>
> class Foo3(object):
> """ working solution 1 : defer the wrapping
> of 'bar' as a staticmethod
> """
> def bar(baaz):
> print baaz
>
> tagada = {'bar': bar}
>
> bar = staticmethod(bar)
>
> def test(self, baaz):
> self.tagada['bar'](baaz)

Neat! I like this one.

>
>
> class Foo4(object):
> """ working solution 2 : use a lambda """
> @staticmethod
> def bar(baaz):
> print baaz
>
> tagada = {'bar': lambda x : Foo4.bar(x)}
>
> def test(self, baaz):
> self.tagada['bar'](baaz)

Huh? How does this one work? After all, while in Foo4 body, the Foo4
does not exist yet? Does lambda defer evaluation to runtime (when it's
executed) or smth?

>
>
> """ and as a "less worse" solution """
>
> def foo5bar(baaz):
> print baaz
>
> class Foo5(object):
> tagada = {'bar': foo5bar}
>
> bar = staticmethod(foo5bar)
>
> def test(self, baaz):
> self.tagada['bar'](baaz)
>

Yes. I probably should have stayed with this one in the first place. I
feel bad for using up bandwidth and people's attention with such stuff...


== 3 of 5 ==
Date: Thurs, Feb 18 2010 5:00 am
From: Bruno Desthuilliers


mk a écrit :
> Bruno Desthuilliers wrote:
(snip)
>> class Foo2(object):
>> """ naive solution : kinda work, BUT will fail
>> with the real code that has plain functions
>> in 'tagada'
>> """
>> @staticmethod
>> def bar(baaz):
>> print baaz
>>
>> tagada = {'bar': bar}
>>
>> def test(self, baaz):
>> self.tagada['bar'].__get__(self)(baaz)
>
> Well I could always do:
>
> if isinstance(self.tagada['bar'], staticmethod):
> self.tagada['bar'].__get__(self)(baaz)
> else:
> self.tagada['bar'](baaz)
>
> But 1. this apparently defeats the purpose of using print_internal_date
> on instance/class in 'normal' way, and 2. I probably shouldn't be doing
> that since using isinstance is apparently like playing with yourself:
> while technically legal, people look at you weirdly. :-)

As far as I'm concerned, this would be a valid use case for isinstance.
But it breaks uniformity and requires quite a lot of mostly useless code.

>>
>> class Foo3(object):
>> """ working solution 1 : defer the wrapping
>> of 'bar' as a staticmethod
>> """
>> def bar(baaz):
>> print baaz
>>
>> tagada = {'bar': bar}
>>
>> bar = staticmethod(bar)
>>
>> def test(self, baaz):
>> self.tagada['bar'](baaz)
>
> Neat! I like this one.

Not me - with the wrapping so far away from the definition, it's too
easy to miss part of the "process" when you come back to this code 6
month later.

>>
>>
>> class Foo4(object):
>> """ working solution 2 : use a lambda """
>> @staticmethod
>> def bar(baaz):
>> print baaz
>>
>> tagada = {'bar': lambda x : Foo4.bar(x)}
>>
>> def test(self, baaz):
>> self.tagada['bar'](baaz)
>
> Huh? How does this one work? After all, while in Foo4 body, the Foo4
> does not exist yet? Does lambda defer evaluation to runtime (when it's
> executed) or smth?

or smth, yes !-)

A lambda expression evals to an ordinary function - just like a def
statement - so Foo4 is not resolved until Foo4.tagada['bar'] is actually
called.

>> """ and as a "less worse" solution """
>>
>> def foo5bar(baaz):
>> print baaz
>>
>> class Foo5(object):
>> tagada = {'bar': foo5bar}
>>
>> bar = staticmethod(foo5bar)
>>
>> def test(self, baaz):
>> self.tagada['bar'](baaz)
>>
>
> Yes. I probably should have stayed with this one in the first place. I
> feel bad for using up bandwidth and people's attention with such stuff...

Why so ? You learned something, I learned something, and quite a few
other people will now have a chance to learn something. Sensible use of
bandwith as far as I'm concerned. wrt/ people's attention, don't worry,
it's up to the reader to pay attention or skip the whole topic !-)

== 4 of 5 ==
Date: Thurs, Feb 18 2010 5:40 am
From: mk


Bruno Desthuilliers wrote:

>>>
>>>
>>> class Foo4(object):
>>> """ working solution 2 : use a lambda """
>>> @staticmethod
>>> def bar(baaz):
>>> print baaz
>>>
>>> tagada = {'bar': lambda x : Foo4.bar(x)}
>>>
>>> def test(self, baaz):
>>> self.tagada['bar'](baaz)
>>
>> Huh? How does this one work? After all, while in Foo4 body, the Foo4
>> does not exist yet? Does lambda defer evaluation to runtime (when it's
>> executed) or smth?
>
> or smth, yes !-)
>
> A lambda expression evals to an ordinary function - just like a def
> statement - so Foo4 is not resolved until Foo4.tagada['bar'] is actually
> called.

This works, but... Foo4.bar in tagada is a staticmethod. So what's
needed is Foo4.bar.__get__(x) (not that I'm that smart, I just got
'staticmethod is not callable' exception).

It appears I have to use __get__ anyway while referring to bar in Foo4
methods:

def testrefer(self, val):
self.bar.__get__(val)
Foo4.bar.__get__(val)

At least I have to do this in my own code:

def testit(self, fname):
self.print_internal_date.__get__(fname + 'c')
PYFileInfo.print_internal_date.__get__(fname + 'c')


Or else I get "TypeError: 'staticmethod' object is not callable".

== 5 of 5 ==
Date: Thurs, Feb 18 2010 6:23 am
From: Bruno Desthuilliers


mk a écrit :
> Bruno Desthuilliers wrote:
>
>>>>
>>>>
>>>> class Foo4(object):
>>>> """ working solution 2 : use a lambda """
>>>> @staticmethod
>>>> def bar(baaz):
>>>> print baaz
>>>>
>>>> tagada = {'bar': lambda x : Foo4.bar(x)}
>>>>
>>>> def test(self, baaz):
>>>> self.tagada['bar'](baaz)
>>>
>>> Huh? How does this one work? After all, while in Foo4 body, the Foo4
>>> does not exist yet? Does lambda defer evaluation to runtime (when
>>> it's executed) or smth?
>>
>> or smth, yes !-)
>>
>> A lambda expression evals to an ordinary function - just like a def
>> statement - so Foo4 is not resolved until Foo4.tagada['bar'] is
>> actually called.
>
> This works, but... Foo4.bar in tagada is a staticmethod. So what's
> needed is Foo4.bar.__get__(x) (not that I'm that smart, I just got
> 'staticmethod is not callable' exception).

Huh ???

class Foo4(object):

@staticmethod
def bar(baaz):
print baaz

tagada = {'bar': lambda x : Foo4.bar(x)}

def test(self, baaz):
self.tagada['bar'](baaz)

>>> f = Foo4()
>>> f.test(42)
42
>>> Foo4.bar(42)
42
>>>

WorksForMe(tm).

> It appears I have to use __get__ anyway while referring to bar in Foo4
> methods:
>
> def testrefer(self, val):
> self.bar.__get__(val)
> Foo4.bar.__get__(val)
>
> At least I have to do this in my own code:
>
> def testit(self, fname):
> self.print_internal_date.__get__(fname + 'c')
> PYFileInfo.print_internal_date.__get__(fname + 'c')
>
>
> Or else I get "TypeError: 'staticmethod' object is not callable".

I think you broke something somewhere. Assuming you're using Python 2.x
(>= 2.3 IIRC), my above code works.

==============================================================================
TOPIC: Creating Import Hooks
http://groups.google.com/group/comp.lang.python/t/9e34f976914880f3?hl=en
==============================================================================

== 1 of 2 ==
Date: Thurs, Feb 18 2010 4:15 am
From: Sreejith K


On Feb 18, 3:49 pm, Jean-Michel Pichavant <jeanmic...@sequans.com>
wrote:
> Sreejith K wrote:
> > On Feb 18, 1:57 pm, Steven D'Aprano
> > <ste...@REMOVE.THIS.cybersource.com.au> wrote:
>
> >> On Thu, 18 Feb 2010 00:03:51 -0800, Jonathan Gardner wrote:
>
> >>> On Feb 17, 10:48 pm, Sreejith K <sreejith...@gmail.com> wrote:
>
> >>>> Hi everyone,
>
> >>>> I need to implement custom import hooks for an application
> >>>> (http://www.python.org/dev/peps/pep-0302/). I want to restrict an
> >>>> application to import certain modules (say socket module). Google app
> >>>> engine is using a module hook to do this (HardenedModulesHook in
> >>>> google/ appengine/tools/dev_appserver.py). But I want to allow that
> >>>> application to use an sdk module (custom) which imports and uses socket
> >>>> module. But the module hook restricts the access by sdk. Finding out,
> >>>> which file is importing a module give a solution?? ie. If the
> >>>> application is importing socket module, I want to restrict it. But if
> >>>> the sdk module is importing socket I want to allow it. Is there any way
> >>>> I can do this ?
>
> >>>> Application
> >>>> ========
> >>>> import sdk
> >>>> import socket               # I dont want to allow this (need to raise
> >>>> ImportError)
>
> >>>> SDK
> >>>> ====
> >>>> import socket               # need to allow this
>
> >>> SDK
> >>> ===
> >>> import socket
>
> >>> App
> >>> ===
> >>> import SDK
> >>> import sys
> >>> socket = sys.modules['socket']
>
> >> I'm not sure, but I think Sreejith wants to prohibit imports from the App
> >> layer while allowing them from the SDK layer, not work around a
> >> prohibition in the SDK layer.
>
> >> In other words, he wants the import hook to do something like this:
>
> >> if module is socket and the caller is not SKD:
> >>     prohibit
> >> else
> >>     allow
>
> >> I could be wrong of course.
>
> >> --
> >> Steven
>
> > @Steven, Thats exactly what I want.. Anyway to do that ??
>
> import sys
> sys.modules['socket'] = None
>
> import socket
> ---------------------------------------------------------------------------
> ImportError                               Traceback (most recent call last)
>
> ImportError: No module named socket
>
> JM

@Jean. Thanks for the reply. But this is not what I wanted. The import
hook already restricts socket imports in applications. But I want them
in sdk package (alone) which is being imported in the application. I
don't want applications to directly use the socket module. That means
I want to make some exceptions for sdk in import hooks.


== 2 of 2 ==
Date: Thurs, Feb 18 2010 4:38 am
From: Jean-Michel Pichavant


Sreejith K wrote:
> On Feb 18, 3:49 pm, Jean-Michel Pichavant <jeanmic...@sequans.com>
> wrote:
>
>> Sreejith K wrote:
>>
>>> On Feb 18, 1:57 pm, Steven D'Aprano
>>> <ste...@REMOVE.THIS.cybersource.com.au> wrote:
>>>
>>>> On Thu, 18 Feb 2010 00:03:51 -0800, Jonathan Gardner wrote:
>>>>
>>>>> On Feb 17, 10:48 pm, Sreejith K <sreejith...@gmail.com> wrote:
>>>>>
>>>>>> Hi everyone,
>>>>>>
>>>>>> I need to implement custom import hooks for an application
>>>>>> (http://www.python.org/dev/peps/pep-0302/). I want to restrict an
>>>>>> application to import certain modules (say socket module). Google app
>>>>>> engine is using a module hook to do this (HardenedModulesHook in
>>>>>> google/ appengine/tools/dev_appserver.py). But I want to allow that
>>>>>> application to use an sdk module (custom) which imports and uses socket
>>>>>> module. But the module hook restricts the access by sdk. Finding out,
>>>>>> which file is importing a module give a solution?? ie. If the
>>>>>> application is importing socket module, I want to restrict it. But if
>>>>>> the sdk module is importing socket I want to allow it. Is there any way
>>>>>> I can do this ?
>>>>>>
>>>>>> Application
>>>>>> ========
>>>>>> import sdk
>>>>>> import socket # I dont want to allow this (need to raise
>>>>>> ImportError)
>>>>>>
>>>>>> SDK
>>>>>> ====
>>>>>> import socket # need to allow this
>>>>>>
>>>>> SDK
>>>>> ===
>>>>> import socket
>>>>>
>>>>> App
>>>>> ===
>>>>> import SDK
>>>>> import sys
>>>>> socket = sys.modules['socket']
>>>>>
>>>> I'm not sure, but I think Sreejith wants to prohibit imports from the App
>>>> layer while allowing them from the SDK layer, not work around a
>>>> prohibition in the SDK layer.
>>>>
>>>> In other words, he wants the import hook to do something like this:
>>>>
>>>> if module is socket and the caller is not SKD:
>>>> prohibit
>>>> else
>>>> allow
>>>>
>>>> I could be wrong of course.
>>>>
>>>> --
>>>> Steven
>>>>
>>> @Steven, Thats exactly what I want.. Anyway to do that ??
>>>
>> import sys
>> sys.modules['socket'] = None
>>
>> import socket
>> ---------------------------------------------------------------------------
>> ImportError Traceback (most recent call last)
>>
>> ImportError: No module named socket
>>
>> JM
>>
>
> @Jean. Thanks for the reply. But this is not what I wanted. The import
> hook already restricts socket imports in applications. But I want them
> in sdk package (alone) which is being imported in the application. I
> don't want applications to directly use the socket module. That means
> I want to make some exceptions for sdk in import hooks.
>
give us your code (the hook import)

in your entry file:

import socket
import sys
sys.modules['sdkSocket'] = sys.modules['socket'] # allow to import
socket ad sdkSocket
sys.modules['socket'] = None # forbid to import socket
del socket

within your SDK:
import sdkSocket # actually the socket module

print sdkSocket.__file__
'/usr/lib/python2.5/socket.pyc'

JM

==============================================================================
TOPIC: Help with lambda
http://groups.google.com/group/comp.lang.python/t/c11c0f7edbed2078?hl=en
==============================================================================

== 1 of 5 ==
Date: Thurs, Feb 18 2010 4:28 am
From: lallous


Hello,

I am still fairly new to Python. Can someone explain to me why there
is a difference in f and g:

def make_power(n):
return lambda x: x ** n

# Create a set of exponential functions
f = [lambda x: x ** n for n in xrange(2, 5)]
g = [make_power(n) for n in xrange(2, 5)]

print f[0](3), f[1](3)
print g[0](3), g[1](3)


I expect to have "f" act same like "g".

Thanks


== 2 of 5 ==
Date: Thurs, Feb 18 2010 4:47 am
From: Arnaud Delobelle


lallous <elias.bachaalany@gmail.com> writes:

> Hello,
>
> I am still fairly new to Python. Can someone explain to me why there
> is a difference in f and g:
>
> def make_power(n):
> return lambda x: x ** n
>
> # Create a set of exponential functions
> f = [lambda x: x ** n for n in xrange(2, 5)]
> g = [make_power(n) for n in xrange(2, 5)]
>
> print f[0](3), f[1](3)
> print g[0](3), g[1](3)
>
>
> I expect to have "f" act same like "g".
>
> Thanks

It's a FAQ! Except I don't think it's in the official Python FAQ, but
it ought to be.

The reason (very quickly) is that each time you call make_power() you
create a new name 'n' which is bound to a different value each time,
whereas in f:

[lambda x: x ** n for n in xrange(2, 5)]

The 'n' is the same name for each of the lambda functions and so is
bound to the same value, which by the end of the loop is 4. So each of
the lambdas in the list f is the same as:

lambdsa x; x**4

after the end of the list comprehension.

The usual fix for this is to change f to:

f = [lambda x, n=n: x ** n for n in xrange(2, 5)]

I'll let you think why this works.

HTH

--
Arnaud


== 3 of 5 ==
Date: Thurs, Feb 18 2010 4:52 am
From: lallous


Yes it should be listed somewhere, now I get it. Thanks Arnaud.

--
Elias

On Feb 18, 1:47 pm, Arnaud Delobelle <arno...@googlemail.com> wrote:
> lallous <elias.bachaal...@gmail.com> writes:
> > Hello,
>
> > I am still fairly new to Python. Can someone explain to me why there
> > is a difference in f and g:
>
> > def make_power(n):
> >     return lambda x: x ** n
>
> > # Create a set of exponential functions
> > f = [lambda x: x ** n for n in xrange(2, 5)]
> > g = [make_power(n) for n in xrange(2, 5)]
>
> > print f[0](3), f[1](3)
> > print g[0](3), g[1](3)
>
> > I expect to have "f" act same like "g".
>
> > Thanks
>
> It's a FAQ!  Except I don't think it's in the official Python FAQ, but
> it ought to be.
>
> The reason (very quickly) is that each time you call make_power() you
> create a new name 'n' which is bound to a different value each time,
> whereas in f:
>
>     [lambda x: x ** n for n in xrange(2, 5)]
>
> The 'n' is the same name for each of the lambda functions and so is
> bound to the same value, which by the end of the loop is 4.  So each of
> the lambdas in the list f is the same as:
>
>     lambdsa x; x**4
>
> after the end of the list comprehension.
>
> The usual fix for this is to change f to:
>
> f = [lambda x, n=n: x ** n for n in xrange(2, 5)]
>
> I'll let you think why this works.
>
> HTH
>
> --
> Arnaud


== 4 of 5 ==
Date: Thurs, Feb 18 2010 4:56 am
From: "D'Arcy J.M. Cain"


On Thu, 18 Feb 2010 04:28:00 -0800 (PST)
lallous <elias.bachaalany@gmail.com> wrote:
> def make_power(n):
> return lambda x: x ** n

Hint: type(make_power(2))

Did you expect that to return "int"?

> # Create a set of exponential functions
> f = [lambda x: x ** n for n in xrange(2, 5)]
> g = [make_power(n) for n in xrange(2, 5)]

The result of make_power(n) is a function that raises it's argument to
the power of n. I don't know what you are trying to do. Maybe this?

g = [make_power(n)(2) for n in xrange(2, 5)]
or
g = [make_power(2)(n) for n in xrange(2, 5)]

--
D'Arcy J.M. Cain <darcy@druid.net> | Democracy is three wolves
http://www.druid.net/darcy/ | and a sheep voting on
+1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner.


== 5 of 5 ==
Date: Thurs, Feb 18 2010 5:08 am
From: lallous


On Feb 18, 1:56 pm, "D'Arcy J.M. Cain" <da...@druid.net> wrote:
> On Thu, 18 Feb 2010 04:28:00 -0800 (PST)
>
> lallous <elias.bachaal...@gmail.com> wrote:
> > def make_power(n):
> >     return lambda x: x ** n
>
> Hint: type(make_power(2))
>
> Did you expect that to return "int"?
>

No, I expect to see a specialized function.

> > # Create a set of exponential functions
> > f = [lambda x: x ** n for n in xrange(2, 5)]
> > g = [make_power(n) for n in xrange(2, 5)]
>
> The result of make_power(n) is a function that raises it's argument to
> the power of n.  I don't know what you are trying to do.  Maybe this?
>
> g = [make_power(n)(2) for n in xrange(2, 5)]
> or
> g = [make_power(2)(n) for n in xrange(2, 5)]
>


What I am trying to do is generate different functions.

If you're curious, I was playing with ctypes and wanted to see how it
handles C<->Python callbacks:

CB_T = WINFUNCTYPE(c_int, c_int)
many_cb_t = CFUNCTYPE(c_int, c_int, CB_T)
many_cb = many_cb_t(addressof(c_void_p.in_dll(dll, "many_cb")))
#ANY_SIMPLER

def make_power(n):
return lambda x: x ** n

cbs = [CB_T(make_power(n)) for n in xrange(0, 1000)]
cbs.append(None)

many_cb(3, *cbs)

And the C code in a shared lib:

int many_cb(int value, ...)
{
va_list va;
va = va_start(va, value);
cb_t cb;
int s = 0;
while ( (cb = va_arg(va, cb_t)) != NULL)
{
printf("calling %p", cb);
int r = cb(value);
s += r;
printf(", r=%d\n", r);
}
va_end(va);
return s;
}

Speaking of that, anyone has an idea how to make simpler the line with
#ANY_SIMPLER?

I try: many_cb = CB_T.in_dll(dll, "many_cb") <- but that seems to work
with data items only.

==============================================================================
TOPIC: Using class attributes
http://groups.google.com/group/comp.lang.python/t/9bd1d65c8f8625ec?hl=en
==============================================================================

== 1 of 2 ==
Date: Thurs, Feb 18 2010 4:39 am
From: Arnaud Delobelle


Leo Breebaart <leo@lspace.org> writes:

> Arnaud Delobelle <arnodel@googlemail.com> writes:
>
>> Descriptors to the rescue :)
>>
>> def read_body_from(filename):
>> print "** loading content **"
>> return "<content of '%s'>" % filename
>>
>> # This is a kind of class property
>> class TemplateFilename(object):
>> def __get__(self, obj, cls):
>> return "%s.tmpl" % cls.__name__
>>
>> # And this is a kind of cached class property
>> class TemplateBody(object):
>> def __get__(self, obj, cls):
>> try:
>> return cls._body
>> except AttributeError:
>> cls._body = read_body_from(cls.template_filename)
>> return cls._body
>>
>> class Foo(object):
>> template_filename = TemplateFilename()
>> template_body = TemplateBody()
>>
>> class FooA(Foo):
>> pass
>>
>> class FooB(Foo):
>> pass
>
> Very enlightening, thanks!
>
> By the way, I completely agree with the other posters in this
> thread that intricate solutions such as this are likely to be
> overkill, especially since at this point I have no idea if the
> inefficiency of reading those templates multiple times would at
> all matter (frankly, I'd doubt it). But it's certainly been
> educational to learn about these techniques.

Writing programs is a great way to keep learning :)

> One observation: if I implement the descriptor solution as given
> above, the code works perfectly, but running the code through
> pychecker now causes an error, because that again causes an
> attempt to read from the non-existant base class template file
> "Foo.tmpl"...

As someone said before, you could just provide a dummy Foo.tmpl file.

--
Arnaud


== 2 of 2 ==
Date: Thurs, Feb 18 2010 5:27 am
From: Leo Breebaart


Arnaud Delobelle <arnodel@googlemail.com> writes:

> > One observation: if I implement the descriptor solution as
> > given above, the code works perfectly, but running the code
> > through pychecker now causes an error, because that again
> > causes an attempt to read from the non-existant base class
> > template file "Foo.tmpl"...

It's not just pychecker that doesn't like the descriptor
solution: pydoc now also crashes with the same IOError. :-)


> As someone said before, you could just provide a dummy Foo.tmpl
> file.

A pragmatic solution, but one that smells bad to me. All this
started because I didn't want my program to read files more than
once, but I also don't want it to read files it doesn't have to
read (and that don't even need to exist) in the first place!

I'll just go back to the original instance-based lazy evaluation
and caching solution now -- I never really had a big problem with
that.

My thanks again to all of you for helping me out with this.

--
Leo Breebaart <leo@lspace.org>

==============================================================================
TOPIC: DO YOU WANT TO BUY A CELL PHONE?
http://groups.google.com/group/comp.lang.python/t/6595e1a364b80ee9?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Feb 18 2010 4:44 am
From: soniyaa 1111

HI FRIENDS,,,,
This site, http://www.shoppingreps.com?SourceId=1259, allows customers
to work as group representative to a group of people. It is a
fantastic idea. I want to buy a cell phone and I registered my
intention. I am waiting for more than 1 week but I didn't get any
email or any other information about my group. I am supposed to get a
chance for bargaining in my city. I know a couple of store where I can
bargain very well quite interesting. This is the site see for yourself
http://www.shoppingreps.com?SourceId=1259

==============================================================================
TOPIC: Referring to class methods in class attributes
http://groups.google.com/group/comp.lang.python/t/bd71264b6022765c?hl=en
==============================================================================

== 1 of 3 ==
Date: Thurs, Feb 18 2010 4:47 am
From: mk


Bruno Desthuilliers wrote:
>> Thanks, that worked. But in order to make it work I had to get rid of
>> 'self' in print_internal_date signature
>
> Indeed. Using it that way, the print_internal_date will not be wrapped
> in a method object.

Hold on! How does Python know what to wrap and what not to wrap,
assuming of course programmer doesn't use @classmethod or @staticmethod?
Bc self has no special significance, it's just a (strong) convention,
Python can't know what's the first argument of a function supposed to
be, self or regular argument, and therefore it has no way of
differentiating between functions (defined in class body) designed to
become methods and those that are not?

Where can I read on Python internals like this (aside from post of
yours, that is)? Bc frankly skimming http://docs.python.org/reference/
didn't give me impression that a lot on the subject is there (well
there's some, I found smth akin to your explanation below, although
yours is way more readable)?

Thanks for explanation below -- I'm going to ask some related questions.

> Mmmm... Let's try to explain the whole damn thing. It's really (and IMHO
> beautifully) simple once you get it, but I agree it's a bit peculiar
> when compared to most mainstream OO languages.
>
> The first thing is that the def statement *always* yield a function
> object. Always. If you don't believe it, try the following snippet:
>
> class Foo(object):
> def bar(self):
> return "baaz"
>
> print Foo.__dict__.keys()
> print type(Foo.__dict__['bar'])

Just one thing here:

>>> Foo.bar
<unbound method Foo.bar>

Huh?! Why does it say 'unbound' method? Shouldn't that be bound method
(bound to Foo, that is)?

> So, why is it that type(Foo.bar) != type(Foo.__dict__['bar']) ?

>>> type(Foo.__dict__['bar'])
<type 'function'>
>>> type(Foo.bar)
<type 'instancemethod'>

instancemethod - now that's something new.


> The
> answer is : attribute lookup rules and the descriptor protocol.
>
> To make a long story short, the descriptor protocol specify that, when,
> during an attribute lookup, a name resolves to a class attribute AND
> this attribute has a __get__ method, then this __get__ method is called
> (with either the instance or None and the class itself as arguments)

Depending, I assume, on whether this is instance call | class method
call, respectively?

Hmm why does the __get__ receive class as argument on top of instance |
None? After all, when having an instance, the class can always be found
by instance.__class__ ? Is this for sake of class methods?

Python is science, I gather: an answer to one question bears another 10
questions.

> and whatever it returns becomes the result of the attribute lookup. This
> mechanism is what provides support for computed attributes.
>
> Now the trick is that the function type do implement the descriptor
> protocol. So when a function is an attribute of a class object and you
> try to access it as an attribute of either the class itself or an
> instance of the class, it's __get__ method is called with the instance
> (or None) and the class.

> Having access to itself (of course),

Quick question: how does a function access itself? Aside from rejected
PEP (http://www.python.org/dev/peps/pep-3130/) I don't see the way of
accessing itself outside globals() (and even then how would a function
know its name -- well it shouldn't care about it really, as function
object doesn't care how it's labelled, right?). Or does in "real Python"
func's __get__ receive its own function (func) as an argument, like in
your example implementation below?

> the
> instance (if there's one) and the class, it's easy for it to wrap all
> this into a method object. Which is itself a callable object, that when
> called mostly inject the instance as first object in the argument's list
> and returns the result of calling the wrapped function object.

Aha! So that's the mechanism that makes self magically appear in an
argument list! I always wondered how it worked. !!THANKS!!


> My 2 cents...

Well, Bruno -- that was more like $200!

Regards,
mk

== 2 of 3 ==
Date: Thurs, Feb 18 2010 5:30 am
From: Steve Holden


mk wrote:
> Bruno Desthuilliers wrote:
>>> Thanks, that worked. But in order to make it work I had to get rid of
>>> 'self' in print_internal_date signature
>>
>> Indeed. Using it that way, the print_internal_date will not be wrapped
>> in a method object.
>
> Hold on! How does Python know what to wrap and what not to wrap,
> assuming of course programmer doesn't use @classmethod or @staticmethod?
> Bc self has no special significance, it's just a (strong) convention,
> Python can't know what's the first argument of a function supposed to
> be, self or regular argument, and therefore it has no way of
> differentiating between functions (defined in class body) designed to
> become methods and those that are not?
>
> Where can I read on Python internals like this (aside from post of
> yours, that is)? Bc frankly skimming http://docs.python.org/reference/
> didn't give me impression that a lot on the subject is there (well
> there's some, I found smth akin to your explanation below, although
> yours is way more readable)?
>
> Thanks for explanation below -- I'm going to ask some related questions.
>
>> Mmmm... Let's try to explain the whole damn thing. It's really (and IMHO
>> beautifully) simple once you get it, but I agree it's a bit peculiar
>> when compared to most mainstream OO languages.
>>
>> The first thing is that the def statement *always* yield a function
>> object. Always. If you don't believe it, try the following snippet:
>>
>> class Foo(object):
>> def bar(self):
>> return "baaz"
>>
>> print Foo.__dict__.keys()
>> print type(Foo.__dict__['bar'])
>
> Just one thing here:
>
>>>> Foo.bar
> <unbound method Foo.bar>
>
> Huh?! Why does it say 'unbound' method? Shouldn't that be bound method
> (bound to Foo, that is)?
>
No. The "unbound method" means it's a callable class attribute. The
significance of "unbound" is that no specific instance is attached.

>> So, why is it that type(Foo.bar) != type(Foo.__dict__['bar']) ?
>
>>>> type(Foo.__dict__['bar'])
> <type 'function'>
>>>> type(Foo.bar)
> <type 'instancemethod'>
>
> instancemethod - now that's something new.
>
Well "instancemethod" is just the type of the attribute. If you create a
Foo instance, its bar method also has type instancemethod, even though
it's a *bound* method:

>>> foo = Foo()
>>> foo
<__main__.Foo object at 0x7ff2a16c>
>>> foo.bar
<bound method Foo.bar of <__main__.Foo object at 0x7ff2a16c>>
>>> type(foo.bar)
<type 'instancemethod'>
>>>

Note that it's only when the method is looked up *from an instance of
the class* does the interpreter create the bound method. And remember
that this is behavior that's specific to Python 2.
>
>> The
>> answer is : attribute lookup rules and the descriptor protocol.
>>
>> To make a long story short, the descriptor protocol specify that, when,
>> during an attribute lookup, a name resolves to a class attribute AND
>> this attribute has a __get__ method, then this __get__ method is called
>> (with either the instance or None and the class itself as arguments)
>
> Depending, I assume, on whether this is instance call | class method
> call, respectively?
>
Yes.

> Hmm why does the __get__ receive class as argument on top of instance |
> None? After all, when having an instance, the class can always be found
> by instance.__class__ ? Is this for sake of class methods?
>
When Bruno wrote "... AND this attribute has a __get__ method ...", the
__get__method has to be defined on the attribute's class - the
interpreter won't even look at the instance when trying to resolve the
reference. But inheritance, of course, means that the same __get__
method may be used by several classes, and when there is no instance the
specific (sub)class in question must be identifiable. So you got that right.

> Python is science, I gather: an answer to one question bears another 10
> questions.
>
Yes, but it isn't quite "turtles all the way down". Ultimately the
behavior we are discussing is hard-wired into the interpreter at the
__getattribute__ level.

>> and whatever it returns becomes the result of the attribute lookup. This
>> mechanism is what provides support for computed attributes.
>>
>> Now the trick is that the function type do implement the descriptor
>> protocol. So when a function is an attribute of a class object and you
>> try to access it as an attribute of either the class itself or an
>> instance of the class, it's __get__ method is called with the instance
>> (or None) and the class.
>
>> Having access to itself (of course),
>
> Quick question: how does a function access itself? Aside from rejected
> PEP (http://www.python.org/dev/peps/pep-3130/) I don't see the way of
> accessing itself outside globals() (and even then how would a function
> know its name -- well it shouldn't care about it really, as function
> object doesn't care how it's labelled, right?). Or does in "real Python"
> func's __get__ receive its own function (func) as an argument, like in
> your example implementation below?
>
The function is an object of type function, so the lookup triggers a
call to the __get__() method of the function's class, providing the
instance (that is the function that is being called) as the first argument.

>> the
>> instance (if there's one) and the class, it's easy for it to wrap all
>> this into a method object. Which is itself a callable object, that when
>> called mostly inject the instance as first object in the argument's list
>> and returns the result of calling the wrapped function object.
>
> Aha! So that's the mechanism that makes self magically appear in an
> argument list! I always wondered how it worked. !!THANKS!!
>
>
>> My 2 cents...
>
> Well, Bruno -- that was more like $200!
>
I agree, this is stuff that's hard to understand, and Bruno's
explanations are most helpful.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/

== 3 of 3 ==
Date: Thurs, Feb 18 2010 5:34 am
From: Bruno Desthuilliers


mk a écrit :
> Bruno Desthuilliers wrote:
>>> Thanks, that worked. But in order to make it work I had to get rid of
>>> 'self' in print_internal_date signature
>>
>> Indeed. Using it that way, the print_internal_date will not be wrapped
>> in a method object.
>
> Hold on! How does Python know what to wrap and what not to wrap,
> assuming of course programmer doesn't use @classmethod or @staticmethod?

answered below - read on, young padawan <g>

> Bc self has no special significance, it's just a (strong) convention,
> Python can't know what's the first argument of a function supposed to
> be, self or regular argument, and therefore it has no way of
> differentiating between functions (defined in class body) designed to
> become methods and those that are not?

Indeed.

> Where can I read on Python internals like this (aside from post of
> yours, that is)? Bc frankly skimming http://docs.python.org/reference/
> didn't give me impression that a lot on the subject is there (well
> there's some, I found smth akin to your explanation below, although
> yours is way more readable)?

Thanks <blush />

> Thanks for explanation below -- I'm going to ask some related questions.
>
>> Mmmm... Let's try to explain the whole damn thing. It's really (and IMHO
>> beautifully) simple once you get it, but I agree it's a bit peculiar
>> when compared to most mainstream OO languages.
>>
>> The first thing is that the def statement *always* yield a function
>> object. Always. If you don't believe it, try the following snippet:
>>
>> class Foo(object):
>> def bar(self):
>> return "baaz"
>>
>> print Foo.__dict__.keys()
>> print type(Foo.__dict__['bar'])
>
> Just one thing here:
>
> >>> Foo.bar
> <unbound method Foo.bar>
>
> Huh?! Why does it say 'unbound' method? Shouldn't that be bound method
> (bound to Foo, that is)?

Yes, but it's not bound to a Foo instance.

>> So, why is it that type(Foo.bar) != type(Foo.__dict__['bar']) ?
>
> >>> type(Foo.__dict__['bar'])
> <type 'function'>

Yeps. That's the function object created by the def statement. Just a
plain old function - expect it's an attribute of class object "Foo".

> >>> type(Foo.bar)
> <type 'instancemethod'>
>
> instancemethod - now that's something new.

Don't let the "<unbound method Foo.bar>" fools you - it's just
instancemethod.__repr__ that issues different wording according to
whether the instancemethod instance is bound or not.

>
>> The
>> answer is : attribute lookup rules and the descriptor protocol.
>>
>> To make a long story short, the descriptor protocol specify that, when,
>> during an attribute lookup, a name resolves to a class attribute AND
>> this attribute has a __get__ method, then this __get__ method is called
>> (with either the instance or None and the class itself as arguments)
>
> Depending, I assume, on whether this is instance call | class method
> call, respectively?

s/call/lookup/

If it's looked up on the class, there's no instance to pass to __get__.

>
> Hmm why does the __get__ receive class as argument on top of instance |
> None? After all, when having an instance, the class can always be found
> by instance.__class__ ? Is this for sake of class methods?

Having access to the class is handy when you don't have the instance.
The point is mostly to let the descriptor know how it has been looked up
and take appropriate decisions based on this - for a definition of
"appropriote" that depends on what the descriptor is intended for .
Remember that this mechanism provides the generic support for all kind
of computed attributes - methods, properties, and whatever you can write
yourself.

> Python is science, I gather: an answer to one question bears another 10
> questions.

That's the case with most technical domains - until you solved enough of
the puzzle to start and see the big picture.

>> and whatever it returns becomes the result of the attribute lookup. This
>> mechanism is what provides support for computed attributes.
>>
>> Now the trick is that the function type do implement the descriptor
>> protocol. So when a function is an attribute of a class object and you
>> try to access it as an attribute of either the class itself or an
>> instance of the class, it's __get__ method is called with the instance
>> (or None) and the class.
>
>> Having access to itself (of course),
>
> Quick question: how does a function access itself?

In that case, it's quite simple: function.__get__ is a method of the
function type, so it's called with 'self' as first argument !-)

> Aside from rejected
> PEP (http://www.python.org/dev/peps/pep-3130/) I don't see the way of
> accessing itself outside globals()

You're confusing the function instance itself with the content of the
def statement's block. The code within the def statement's block has no
access to the function instance that will be built from it, but other
methods of the function instance are, well, ordinary methods.

> (and even then how would a function
> know its name -- well it shouldn't care about it really, as function
> object doesn't care how it's labelled, right?). Or does in "real Python"
> func's __get__ receive its own function (func)

it receives itself, yes. Ordinary method call, nothing magical here -
well, almost...!-).

> as an argument, like in
> your example implementation below?

Exactly.

>> the
>> instance (if there's one) and the class, it's easy for it to wrap all
>> this into a method object. Which is itself a callable object, that when
>> called mostly inject the instance as first object in the argument's list
>> and returns the result of calling the wrapped function object.
>
> Aha! So that's the mechanism that makes self magically appear in an
> argument list! I always wondered how it worked.

Now you know. As far as I'm concerned, I do find this whole mechanism to
be a thing of beauty - instead of special-casing methods, you just use
plain functions and the much more generic descriptor protocol to achieve
the same result - with much more flexibility.

> !!THANKS!!
>
>> My 2 cents...
>
> Well, Bruno -- that was more like $200!

Ok, make it 3 cents then !-)

More seriously, all this is explained in Raymond Hettinger's excellent
'descriptor howto' article, that is linked from the official doc - and
that's how I learned all this.

==============================================================================
TOPIC: NOW Watch Hot Sexy Star Aishwarya rai <NUDE> Bathing Videos In All
Angles.
http://groups.google.com/group/comp.lang.python/t/b09c5f3a101eb90f?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Feb 18 2010 5:33 am
From: "ranga..............."


NOW Watch Hot Sexy Star Aishwarya rai <NUDE> Bathing Videos In All
Angles at

http://blogcreationandhosting.blogspot.com/2009/11/1-per-click-in-adsense-programs.html

< Due to high sex content,I have hidden these videos inside an Image.
In that website,click on big vertical shining image on the right side
of website & watch the videos >

==============================================================================
TOPIC: Python 3.0 usage?
http://groups.google.com/group/comp.lang.python/t/fc5f97fcb89e5474?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Feb 18 2010 5:37 am
From: Philip Semanchuk

On Feb 18, 2010, at 12:20 AM, alex23 wrote:

> MRAB <pyt...@mrabarnett.plus.com> wrote:
>> Python 3.0 had a relatively short run before it was superseded by
>> Python
>> 3.1 due to certain issues, so, IMHO, I wouldn't worry about it unless
>> someone especially requests/requires it.
>
> And even then, I'd just tell them I accept patches :)

Excellent idea. =)

Thanks to all who replied.

Cheers
Philip

==============================================================================
TOPIC: How to efficiently extract information from structured text file
http://groups.google.com/group/comp.lang.python/t/bc8840f8a254056b?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Feb 18 2010 5:39 am
From: Paul McGuire


On Feb 17, 7:38 pm, Steven D'Aprano
<ste...@REMOVE.THIS.cybersource.com.au> wrote:
> On Wed, 17 Feb 2010 17:13:23 -0800, Jonathan Gardner wrote:
> > And once you realize that every program is really a compiler, then you
> > have truly mastered the Zen of Programming in Any Programming Language
> > That Will Ever Exist.
>
> In the same way that every tool is really a screwdriver.
>
> --
> Steven

The way I learned this was:
- Use the right tool for the right job.
- Every tool is a hammer.

-- Paul

==============================================================================
TOPIC: Interesting talk on Python vs. Ruby and how he would like Python to
have just a bit more syntactic flexibility.
http://groups.google.com/group/comp.lang.python/t/9a88c79d4043ba30?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Feb 18 2010 6:15 am
From: Steve Howell


On Feb 18, 1:23 am, Duncan Booth <duncan.bo...@invalid.invalid> wrote:
> Jonathan Gardner <jgard...@jonathangardner.net> wrote:
> > On Feb 17, 12:02 am, Lawrence D'Oliveiro <l...@geek-
> > central.gen.new_zealand> wrote:
> >> In message
> >> <8ca440b2-6094-4b35-80c5-81d000517...@v20g2000prb.googlegroups.com>,
>
> >> Jonathan Gardner wrote:
> >> > I used to think anonymous functions (AKA blocks, etc...) would be a
> >> > nice feature for Python.
>
> >> > Then I looked at a stack trace from a different programming
> >> > language with lots of anonymous functions. (I believe it was perl.)
>
> >> Didn't it have source line numbers in it?
>
> >> What more do you need?
>
> > I don't know, but I tend to find the name of the function I called to
> > be useful. It's much more memorable than line numbers, particularly
> > when line numbers keep changing.
>
> > I doubt it's just me, though.
>
> Some problems with using just line numbers to track errors:
>
> In any language it isn't much use if you get a bug report from a shipped
> program that says there was an error on line 793 but no report of
> exactly which version of the shipped code was being run.
>
> Microsoft love telling you the line number: if IE gets a Javascript
> error it reports line number but not filename, so you have to guess
> which of the HTML page or one of many included files actually had the
> error. Plus the line number that is reported is often slightly off.
>
> Javascript in particular is often sent to the browser compressed then
> uncompressed and eval'd. That makes line numbers completely useless for
> tracking down bugs as you'll always get the line number of the eval.
> Also the way functions are defined in Javascript means you'll often have
> almost every function listed in a backtrace as 'Anonymous'.

If this is an argument against using anonymous functions, then it is a
quadruple strawman.

Shipping buggy code is a bad idea, even with named functions.

Obscuring line numbers is a bad idea, even with named functions.

Having your customers stay on older versions of your software is a bad
idea, even with named functions.

Not being able to know which version of software you're customer is
running is a bad idea, even with named functions.

Of course, using anonymous functions in no way prevents you from
capturing a version number in a traceback. And in most modern source
control systems, it is fairly easy to revert to an old version of that
code.

def factory():
return lambda: 15 / 0

def bar(method):
method()

def foo(method):
bar(method)

def baz(method):
foo(method)

try:
baz(factory())
except:
print 'problem with version 1.234a'
raise

problem with version 1.234a
Traceback (most recent call last):
File "foo.py", line 14, in <module>
baz(factory())
File "foo.py", line 11, in baz
foo(method)
File "foo.py", line 8, in foo
bar(method)
File "foo.py", line 5, in bar
method()
File "foo.py", line 2, in <lambda>
return lambda: 15 / 0
ZeroDivisionError: integer division or modulo by zero

==============================================================================
TOPIC: NOW Watch Hot Sexy Star Aishwarya rai Bathing Videos In All Angles.
http://groups.google.com/group/comp.lang.python/t/daa1fed2a9f2aa91?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Feb 18 2010 6:26 am
From: jaagar


NOW Watch Hot Sexy Star Aishwarya rai Bathing Videos In All Angles at

http://blogcreationandhosting.blogspot.com/2009/11/1-per-click-in-adsense-programs.html

< Due to high sex content,I have hidden these videos inside an Image.
In that website,click on big vertical shining image on the right side
of website & watch the videos >

==============================================================================
TOPIC: unit testing a routine that sends mail
http://groups.google.com/group/comp.lang.python/t/33e5d23bbb8724a3?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Feb 18 2010 6:37 am
From: commander_coder


Hello,

I have a routine that sends an email (this is how a Django view
notifies me that an event has happened). I want to unit test that
routine. So I gave each mail a unique subject line and I want to use
python's mailbox package to look for that subject. But sometimes the
mail gets delivered and sometimes it does not (I use sendmail to send
it but I believe that it is always sent since I can see an entry in
the mail log).

I thought that the mail delivery system was occasionally hitting my
mailbox lock, and that I needed to first sleep for a while. So I
wrote a test that sleeps, then grabs the mailbox and looks through it,
and if the mail is not there then it sleeps again, etc., for up to ten
tries. It is below.

However, I find that if the mail is not delivered on the first try
then it is never delivered, no matter how long I wait. So I think I
am doing mailbox wrong but I don't see how.

The real puzzler for me is that the test reliably fails every third
time. For instance, if I try it six times then it succeeds the first,
second, fourth, and fifth times. I have to say that I cannot
understand this at all but it certainly makes the unit test useless.

I'm using Python 2.6 on an Ubuntu system. If anyone could give me a
pointer to why the mail is not delivered, I sure could use it.

Thanks,
Jim

...................................................................

class sendEmail_test(unittest.TestCase):
"""Test sendEmail()
"""
config = ConfigParser.ConfigParser()
config.read(CONFIG_FN)
mailbox_fn=config.get('testing','mailbox')

def look_in_mailbox(self,uniquifier='123456789'):
"""If the mailbox has a message whose subject line contains
the
given uniquifier then it returns that message and deletes it.
Otherwise, returns None.
"""
sleep_time=10.0 # wait for message to be delivered?
message_found=None
i=0
while i<10 and not(message_found):
time.sleep(sleep_time)
m=mailbox.mbox(self.mailbox_fn)
try:
m.lock()
except Exception, err:
print "trouble locking the mailbox: "+str(err)
try:
for key,message in m.items():
subject=message['Subject'] or ''
print "subject is ",subject
if subject.find(uniquifier)>-1:
print "+++found the message+++ i=",str(i)
message_found=message
m.remove(key)
break
m.flush()
except Exception, err:
print "trouble reading from the mailbox: "+str(err)
m.unlock()
try:
m.unlock()
except Exception, err:
print "trouble unlocking the mailbox: "+str(err)
try:
m.close()
except Exception, err:
print "trouble closing the mailbox: "+str(err)
del m
i+=1
return message_found

def test_mailbox(self):
random.seed()
uniquifier=str(int(random.getrandbits(20)))
print "uniquifier is ",uniquifier # looks different every
time to me
rc=az_view.sendEmail(uniquifier=uniquifier)
if rc:
self.fail('rc is not None: '+str(rc))
found=self.look_in_mailbox(uniquifier)
if not(found):
self.fail('message not found')
print "done"


==============================================================================

You received this message because you are subscribed to the Google Groups "comp.lang.python"
group.

To post to this group, visit http://groups.google.com/group/comp.lang.python?hl=en

To unsubscribe from this group, send email to comp.lang.python+unsubscribe@googlegroups.com

To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.python/subscribe?hl=en

To report abuse, send email explaining the problem to abuse@googlegroups.com

==============================================================================
Google Groups: http://groups.google.com/?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate