Wednesday, February 17, 2010

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

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

comp.lang.python@googlegroups.com

Today's topics:

* Python version of perl's "if (-T ..)" and "if (-B ...)"? - 1 messages, 1
author
http://groups.google.com/group/comp.lang.python/t/8816441f153588dd?hl=en
* Is automatic reload of a module available in Python? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/71d2e8e4a38c3b1d?hl=en
* How to build a list of all modules in standard library? - 1 messages, 1
author
http://groups.google.com/group/comp.lang.python/t/3e92acb24be3e3aa?hl=en
* Referring to class methods in class attributes - 6 messages, 5 authors
http://groups.google.com/group/comp.lang.python/t/bd71264b6022765c?hl=en
* Traversing through variable-sized lists - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/6f56c35ab7103a91?hl=en
* Over(joy)riding - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/d71fbc10c9d1f900?hl=en
* Wrap and intercept function calls - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/8785a4e8d85dd581?hl=en
* MediaWiki to RTF/Word/PDF - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/4ff0e391e0e2f321?hl=en
* mixins and new style classes - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/5e9e7cabc90fed40?hl=en
* The future of "frozen" types as the number of CPU cores increases - 1
messages, 1 author
http://groups.google.com/group/comp.lang.python/t/7ef75c20d1be370d?hl=en
* Interesting talk on Python vs. Ruby and how he would like Python to have
just a bit more syntactic flexibility. - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/9a88c79d4043ba30?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
* string to list when the contents is a list - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/d604be2eee402ced?hl=en
* error trying to join #python on irc.freenode.net - 2 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/6f73186707aafacb?hl=en

==============================================================================
TOPIC: Python version of perl's "if (-T ..)" and "if (-B ...)"?
http://groups.google.com/group/comp.lang.python/t/8816441f153588dd?hl=en
==============================================================================

== 1 of 1 ==
Date: Wed, Feb 17 2010 11:18 am
From: Hrvoje Niksic


Tim Chase <python.list@tim.thechases.com> writes:

> if portion is None:
> content = iter(f)

iter(f) will iterate over lines in the file, which doesn't fit with the
rest of the algorithm. Creating an iterator that iterates over
fixed-size file chunks (in this case of length 1) is where the
two-argument form of iter comes in handy:

content = iter(lambda: f.read(1), '')

==============================================================================
TOPIC: Is automatic reload of a module available in Python?
http://groups.google.com/group/comp.lang.python/t/71d2e8e4a38c3b1d?hl=en
==============================================================================

== 1 of 1 ==
Date: Wed, Feb 17 2010 12:21 pm
From: Terry Reedy


On 2/17/2010 9:27 AM, R (Chandra) Chandrasekhar wrote:
> Dear Folks,
>
> I am currently developing a python program, let us call it "generic.py",
> and I am testing out the functions therein by testing them out
> interactively in the python interpreter by invoking python and doing
>
> import generic
>
> Once I hit an error, I need to revise my file and reload the module using
>
> reload(generic)

Reload is sufficiently flakey that it has been removed in 3.x. The
problem is that it genearally only *partially* replaces the module, so
that some code uses the old version and some the new. Guido tried to
rewrite it but gave up and removed it. The most sensible way to
completely remove a module is to shutdown and restart the interpreter.

> The difference in syntax between invoking import and reload is really
> costing me time and patience.
>
> Therefore, I would like to ask:
>
> 1. Is there a method of auto-reloading a module while developing it and
> testing it with the interactive python interpreter?
>
> 2. Is there a better way of developing a program?

This is what I now do.
Edit
# xxx/module.py

<incrementally written module code>

def _test():
<incrementally added tests>

if __name__ == '__main__': _test()

with IDLE and hit F5 to run and test. IDLE runs the file in a *fresh*
subinterpreter as the main module and then, whether or not an exception
is raised, switches to interactive mode, so one can interactively test
any objects created (before any exception). The switch to interactive
mode after running a file can also be done with a command line switch
when using CPython directly.

Terry Jan Reedy

==============================================================================
TOPIC: How to build a list of all modules in standard library?
http://groups.google.com/group/comp.lang.python/t/3e92acb24be3e3aa?hl=en
==============================================================================

== 1 of 1 ==
Date: Wed, Feb 17 2010 12:28 pm
From: Terry Reedy


On 2/17/2010 9:57 AM, python@bdurham.com wrote:
> We're building a py2exe executable that may need to do some dynamic
> module imports.
> I'm looking for suggestions on how we can mechanically generate a list
> of standard library modules/packages to make sure our build has the full
> set of Python 2.6.4 libraries.

Find the source file for the global module index that comes with the doc
set.

Terry Jan Reedy


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

== 1 of 6 ==
Date: Wed, Feb 17 2010 11:44 am
From: Bruno Desthuilliers


mk a écrit :
> Stephen Hansen wrote:
>
>> You don't have to (and can't) refer to the class within the body.
>> Class statements are sort of... odd. They are code which is directly
>> executed, and the results are then passed into a
>> metaclass/type/whatever and a class object is created. While within
>> the class body, the class doesn't exist yet.
>>
>> But you don't need it to.
>>
>> Just do:
>>
>> 'internal_date': print_internal_date
>>
>> The 'def' is in the same local scope as 'tagdata' is.
>
> 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.

> bc all other functions in
> tagdata have only a single argument:
>
> class PYFileInfo(FileInfo):
> 'python file properties'
>
> def print_internal_date(filename):
> ...
>
> tagdata = {'compiled_fname': lambda x: x + 'c',
> 'size': os.path.getsize,
> 'internal_date': print_internal_date
> }
>
> That looks weird: a method with no 'self'.

It's not a method.

> Hmm that is probably
> seriously wrong.
>
> This obviously means no other method can call it like
> self.print_internal_date(), because self would get passed as first
> argument, yes?

Unless you make it a staticmethod.

> I checked that print_internal_date can be called on an instance, so the
> same method

s/method/function/


> can be seen as:
>
> - class method -- when used in local scope definition like tagdata, or
> - instance method -- when called from an instance or from self?

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'])


So, why is it that type(Foo.bar) != type(Foo.__dict__['bar']) ? 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)
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), 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.

A (naive) implementation of the whole thing might look like this:

class method(object):
def __init__(self, func, instance, cls):
self.im_func = func
self.im_self = instance
self.im_class = cls

def __call__(self, *args, **kw):
# XXX : all sanity checks removed for readability
if self.im_self:
args = (self.im_func,) + args
return self.im_func(*args, **kw)


class function(object):
# ...
def __get__(self, instance, cls):
return method(self, instance, cls)


So, what makes a function a "method" is not being defined in a class
statement's body (well, not directly at least), it's that it is an
attribute of the class. FWIW, the following code is perfectly legal:

class Foo(object):
pass

def func(obj):
print "obj is %s " % obj

Foo.method = func

f = Foo()
f.method()
Foo.method(f)
func(f)

> I wonder if I'm not trying to make Python things it shouldn't be doing,
> but it's the problem at hand that is leading me into this conundrum: all
> other functions for tagdata use single arguments. I should probably code
> around that anyway..

Well, the simple solution is to just leave print_internal_date as a
plain function instead of insisting on making it a method. Python is
100% OO in that everything is an object, but it's not a "pure" OO
language, ie it doesn't require everything to happen in a method. So if
all you need is a function, by all mean just use a function !-)

Now if you really need print_internal_date to be exposed as a method of
PYFileInfo - like, you need polymorphic dispatch - then make it a
staticmethod.

My 2 cents...


== 2 of 6 ==
Date: Wed, Feb 17 2010 12:55 pm
From: John Posner


On 2/17/2010 2:44 PM, Bruno Desthuilliers wrote:
>
> 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.

Very nice writeup, Bruno -- thanks!

<snip>

>
> class method(object):
> def __init__(self, func, instance, cls):
> self.im_func = func
> self.im_self = instance
> self.im_class = cls
>
> def __call__(self, *args, **kw):
> # XXX : all sanity checks removed for readability
> if self.im_self:
> args = (self.im_func,) + args

In the line above, I think you meant:

args = (self.im_self,) + args

-John


== 3 of 6 ==
Date: Wed, Feb 17 2010 1:24 pm
From: Arnaud Delobelle


Bruno Desthuilliers <bdesth.quelquechose@free.quelquepart.fr> writes:

[...]
> class Foo(object):
> def bar(self):
> return "baaz"
>
> print Foo.__dict__.keys()
> print type(Foo.__dict__['bar'])
>
>
> So, why is it that type(Foo.bar) != type(Foo.__dict__['bar']) ? The
> answer is : attribute lookup rules and the descriptor protocol.

It's true of Python 2.X. In Python 3 there are no more unbound method:

Python 3.2a0 (py3k:75274, Oct 7 2009, 20:25:52)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
... def f(self): pass
...
>>> A.f
<function f at 0x445b28>
>>> A.f is A.__dict__['f']
True

--
Arnaud


== 4 of 6 ==
Date: Wed, Feb 17 2010 12:34 pm
From: Bruno Desthuilliers


John Posner a écrit :
> On 2/17/2010 2:44 PM, Bruno Desthuilliers wrote:
>>
> Very nice writeup, Bruno -- thanks!

<blush />

> <snip>
>
>>
>>
>> def __call__(self, *args, **kw):
>> # XXX : all sanity checks removed for readability
>> if self.im_self:
>> args = (self.im_func,) + args
>
> In the line above, I think you meant:
>
> args = (self.im_self,) + args

oops :?

Yes, indeed. Thanks for the correction.


== 5 of 6 ==
Date: Wed, Feb 17 2010 2:04 pm
From: Ben Finney


Bruno Desthuilliers <bdesth.quelquechose@free.quelquepart.fr> writes:

> 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.
[…]

Bruno, that's the first time I've understood the descriptor protocol, or
even understood *why* the descriptor protocol is important.

Could you please post (a version of) this as a separate article
somewhere? A weblog post, or a new thread in this forum, or in the
documentation? Somewhere that web searches will find it prominently when
searching for the Python descriptor protocol.

Thank you.

--
\ "I don't want to live peacefully with difficult realities, and |
`\ I see no virtue in savoring excuses for avoiding a search for |
_o__) real answers." —Paul Z. Myers, 2009-09-12 |
Ben Finney


== 6 of 6 ==
Date: Wed, Feb 17 2010 2:14 pm
From: Mark Lawrence


Ben Finney wrote:
> Bruno Desthuilliers <bdesth.quelquechose@free.quelquepart.fr> writes:
>
>> 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.
> […]
>
> Bruno, that's the first time I've understood the descriptor protocol, or
> even understood *why* the descriptor protocol is important.
>
> Could you please post (a version of) this as a separate article
> somewhere? A weblog post, or a new thread in this forum, or in the
> documentation? Somewhere that web searches will find it prominently when
> searching for the Python descriptor protocol.
>
> Thank you.
>

I'll second, third and fourth this request. More please Bruno, or from
anybody similarly qualified.

Thanks very much.

Mark Lawrence.


==============================================================================
TOPIC: Traversing through variable-sized lists
http://groups.google.com/group/comp.lang.python/t/6f56c35ab7103a91?hl=en
==============================================================================

== 1 of 2 ==
Date: Wed, Feb 17 2010 12:54 pm
From: Andrej Mitrovic


On Feb 17, 8:24 pm, John Posner <jjpos...@optimum.net> wrote:
> On 2/17/2010 1:10 PM, Andrej Mitrovic wrote:
>
>
>
> > Hi,
>
> > I couldn't figure out a better description for the Subject line, but
> > anyway, I have the following:
>
> > _num_frames = 32
> > _frames = range(0, _num_frames) # This is a list of actual objects,
> > I'm just pseudocoding here.
> > _values = [0, 1, 2, 3, 4]
>
> > I want to call a function of _frames for each frame with a _values
> > argument, but in a way to "spread out" the actual values.
>
> > I would want something similar to the following to be called:
>
> > _frames[0].func(_values[0])
> > _frames[1].func(_values[0])
> > _frames[2].func(_values[0])
> > _frames[3].func(_values[0])
> > _frames[4].func(_values[1])
> > _frames[5].func(_values[1])
> > _frames[6].func(_values[1])
> > _frames[7].func(_values[1])
> > _frames[8].func(_values[2])
> > ...etc...
>
> The lines above show that you are using two different series of index
> values. Each function call (more properly, "method call") has the form:
>
>    frames[INDEX_FROM_FIRST_SERIES].func(INDEX_FROM_SECOND_SERIES)
>
> (I've dropped the underscores in the names, for simplicity.) You're
> getting hung up trying to keep the two series of index values in sync.
> But you don't really need to. More below ...
>
>
>
>
>
> > Both the _values list and _frames list can be of variable and uneven
> > size, which is what is giving me the problems. I'm using Python 2.6.
>
> > I've tried the following workaround, but it often gives me inaccurate
> > results (due to integer division), so I had to add a safety check:
>
> > num_frames = 32
> > values = [0, 1, 2, 3, 4]
> > offset_step = num_frames / len(values)
> >      for index in xrange(0, num_frames):
> >          offset = index / offset_step
> >          if offset>  offset_values[-1]:
> >              offset = offset_values[-1]
> >          frames[index].func(values[offset])
>
> > There has to be a better way to do this. I'd appreciate any help.
> > Cheers!
>
> As you've shown above, a "for" loop takes care of the first series of
> index values:
>
>    for index in xrange(num_frames):       # "0" arg unnecessary
>        frames[index].func(INDEX_FROM_SECOND_SERIES)
>
> The second series of index values needs to look like this:
>
>    0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3 ...
>
> The trick is not to worry about matching the second series to the first
> series. Instead, create an "infinite" second series using a Python
> generator, and use as many of its values as you need. Don't worry about
> the unused values, because the series isn't *really* infinite. :-)
>
> Here's an easy way to create the generator
>
>    import itertools
>    second_series_gen = (i/4 for i in itertools.count())
>
> Now, every time you need another number from this series, use its next()
> method. So the above code becomes:
>
>    for index in xrange(num_frames):
>        frames[index].func(second_series_gen.next())
>
> -John

That's a cool trick, but maybe I wasn't specific enough. The values
series are the range of values that the frames.func() function should
use, it should not overflow, and I would want the function to use as
evenly distributed number of values as possible from the first series.
The "0000,1111" was just an example. Let me see if I can be more
specific:

values = [2, 3, 4]
frames = [obj1, obj2, obj3, obj4, obj5, obj6]

And the calls:

frames[0].func(values[0]) # func.(values[2])
frames[1].func(values[0]) # func.(values[2])
frames[2].func(values[1]) # func.(values[3])
frames[3].func(values[1]) # func.(values[3])
frames[4].func(values[2]) # func.(values[4])
frames[5].func(values[2]) # func.(values[4])


However the values list might have an uneven number of items. I would
like to make it as evenly distributed as possible, e.g.:

values = [-2, -1, 0]
frames = [obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8]

frames[0].func(values[0]) # func.(values[-2])
frames[1].func(values[0]) # func.(values[-2])
frames[2].func(values[1]) # func.(values[-2])
frames[3].func(values[1]) # func.(values[-1])
frames[4].func(values[1]) # func.(values[-1])
frames[5].func(values[2]) # func.(values[-1])
frames[6].func(values[2]) # func.(values[0])
frames[7].func(values[2]) # func.(values[0])


I'll be even more specific. I have a Minimum and Maximum value that
the user enters. The frame.func() function is a "translate" function,
it basically moves a frame in the application in one direction or
another depending on the argument value. So frame[0].func(2) would
move the frame[0] 2 pixels to the right. So what I want is the
function to create a smooth transition of all the frames from the
Minimum to the Maximum value. If minimum was 0, and maximum was 10,
I'd want the first frame moved 0 pixels (it stays in place), the last
frame to move 10 pixels, and the frames between are gradually moved
from 1 pixels to 9 pixels relative from their positions.

Perhaps I'm just overcomplicating. I'll have a look at some drawing
apps and see how they've implemented drawing straight lines under an
angle, I guess that could be called a gradual change of values.

Thanks for all the suggestions everyone, I'll have a look at the rest
shortly.


== 2 of 2 ==
Date: Wed, Feb 17 2010 2:56 pm
From: Dave Angel


Andrej Mitrovic wrote:
> On Feb 17, 8:24 pm, John Posner <jjpos...@optimum.net> wrote:
>
>> On 2/17/2010 1:10 PM, Andrej Mitrovic wrote:
>>
>> <snip>
>
> However the values list might have an uneven number of items. I would
> like to make it as evenly distributed as possible, e.g.:
>
> values =-2, -1, 0]
> frames =obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8]
>
> frames[0].func(values[0]) # func.(values[-2])
> frames[1].func(values[0]) # func.(values[-2])
> frames[2].func(values[1]) # func.(values[-2])
> frames[3].func(values[1]) # func.(values[-1])
> frames[4].func(values[1]) # func.(values[-1])
> frames[5].func(values[2]) # func.(values[-1])
> frames[6].func(values[2]) # func.(values[0])
> frames[7].func(values[2]) # func.(values[0])
>
>
> I'll be even more specific. I have a Minimum and Maximum value that
> the user enters. The frame.func() function is a "translate" function,
> it basically moves a frame in the application in one direction or
> another depending on the argument value. So frame[0].func(2) would
> move the frame[0] 2 pixels to the right. So what I want is the
> function to create a smooth transition of all the frames from the
> Minimum to the Maximum value. If minimum was 0, and maximum was 10,
> I'd want the first frame moved 0 pixels (it stays in place), the last
> frame to move 10 pixels, and the frames between are gradually moved
> from 1 pixels to 9 pixels relative from their positions.
>
> Perhaps I'm just overcomplicating. I'll have a look at some drawing
> apps and see how they've implemented drawing straight lines under an
> angle, I guess that could be called a gradual change of values.
>
> Thanks for all the suggestions everyone, I'll have a look at the rest
> shortly.
>
>
I think you're overcomplicating. If you have 27 frames, and you want
frame 0 to move 0 pixels, and frame 27 to move 10 pixels, then you want
to move frame[i] by i*10/27. And since you do the multiply first, the
fact that Python 2.x division gives you integers isn't a problem.

There are fancier methods for drawing lines (bresenham for example), but
the main purpose of them is to to avoid multiply and divide, as well as
floats. But in Python, an integer multiply is just as fast as an add or
subtract, so there's no point.

DaveA

==============================================================================
TOPIC: Over(joy)riding
http://groups.google.com/group/comp.lang.python/t/d71fbc10c9d1f900?hl=en
==============================================================================

== 1 of 1 ==
Date: Wed, Feb 17 2010 12:00 pm
From: Bruno Desthuilliers


mk a �crit :
> Bruno Desthuilliers wrote:
>> mk a �crit :
>>> P.S. Method resolution order in Python makes me want to kill small
>>> kittens.
>>
>> mro is only a "problem" when using MI.
>
> Oh sure! And I have the impression that multiple inheritance is not used
> all that often. What (some) Python code I've read in open source
> projects typically uses single inheritance.

Single inheritance does indeed cover most of the needs - and FWIW, even
single inheritance is not used as much in Python as in some other more
mainstream OOPLs. This comes partly from duck typing - inheritance is
only used for implementation inheritance, not for type-based polymorphic
dispatch -, and partly from Python's support for composition/delegation
(thru __getattr__). Also - as you noticed - single inheritance is easier
to grasp, and Python's philosophy really values simplicity, readability,
maintainability, and coder's mental health !-)

> Nevertheless MI is there in Python, might be useful in some cases and
> Guido put it there for some reason,

Indeed. As with most Python's "advanced" features, it's there so you can
use it when appropriate.

> so Citizens Aspiring To Become
> Pythonistas like me work to learn it.

FWIW, I very rarely had to use it myself in almost 10 years of Python
programming - main exceptions being Zope2 stuff (which is IMHO highly
unpythonic) and a couple mixin classes here and there.

==============================================================================
TOPIC: Wrap and intercept function calls
http://groups.google.com/group/comp.lang.python/t/8785a4e8d85dd581?hl=en
==============================================================================

== 1 of 1 ==
Date: Wed, Feb 17 2010 12:57 pm
From: Terry Reedy


On 2/17/2010 11:04 AM, Dan Yamins wrote:
> Really, nobody has any idea about this? (Sorry to repost.)

> On Tue, Feb 16, 2010 at 7:29 PM, Dan Yamins <dyamins@gmail.com
> <mailto:dyamins@gmail.com>> wrote:
>
> Hi:
>
> I'm wondering what the best way to wrap and modify function calls
> is. Essentially what I want to achieve is to have a function like
> this:
>
> def Wrap(frame,event,arg):
> if event == 'call':
> result = PerformCheck(GetArgumentsFromFrame(frame))
> if Condition(result):
> return result
> else:
> return [normal function call]
>
> called whenever a "call" event is about to occur.

For yourself as interpreter, execute the above for every call.

For CPython, alternative 1 is to create a custom interpreter to change
(wrap) the interpretation of the call-function bytecode in the ceval
loop. That is its 'call event', and I believe this would catch every
explicit f(args) call and only such calls.

Python has no general metasyntax for changing the semantics of its
syntax. The __xx__ methods are special cases for the corresponding
operators *and* the corresponding user-defined class. The '__call__'
method of a class applies to instances of that class. Alternative 2:

class func_wrap:
def __init__(self, func):
self._func = func
def __call__(self, args, kwds):
result = PerformCheck(args, kwds)
if Condition(result):
return result
else:
return self._func(*args,**kwds)

Now wrap *every* function you are interested in. Builtin functions are
no problem; methods of builtin classes cannont be wrapped without
subclassing.

Terry Jan Reedy

> When I say "return result" I mean: return that data object instead
> of what the function would have returned, and prevent execution of
> the function.
>
> Is there any way to do this using sys.settrace? Or perhaps
> something from the bdb or pbd module?
>
>
> In other words, what I'm looking for is a way to intercept all function
> calls with a "wrapper" -- like one can do using settrace and other
> debugging methods -- but, unlike the debugging methods, have the
> "wrapping" function actually be able to intervene in the stack and, for
> instance, conditionally replace the function call's return with
> something determined in the wrapping function and prevent the function
> call's execution. I want to be able to do this by setting a single
> system-wide (or at any rate, thread-wide) value, like with settrace, and
> not have to modify individual functions one by one.
>
> Could I, for example, set a settrace function that somehow modifies the
> stack? Or is there some much better way to do this? Or, if someone can
> tell me that this can't be done without having to roll my own
> implementation of the Python interpreter, that would be great to know too.
>
> Thanks again,
> Dan
>

==============================================================================
TOPIC: MediaWiki to RTF/Word/PDF
http://groups.google.com/group/comp.lang.python/t/4ff0e391e0e2f321?hl=en
==============================================================================

== 1 of 3 ==
Date: Wed, Feb 17 2010 1:00 pm
From: Josh English


I have several pages exported from a private MediaWiki that I need to
convert to a PDF document, or an RTF document, or even a Word
document.

So far, the only Python module I have found that parses MediaWiki
files is mwlib, which only runs on Unix, as far as I can tell. I'm
working on Windows here.

Has anyone heard of a module that parses wiki markup and transforms
it? Or am I looking at XSLT?

Josh


== 2 of 3 ==
Date: Wed, Feb 17 2010 1:35 pm
From: "Diez B. Roggisch"


Am 17.02.10 22:00, schrieb Josh English:
> I have several pages exported from a private MediaWiki that I need to
> convert to a PDF document, or an RTF document, or even a Word
> document.
>
> So far, the only Python module I have found that parses MediaWiki
> files is mwlib, which only runs on Unix, as far as I can tell. I'm
> working on Windows here.

I think you stand a chance making it run under windows using mingw.
Might be a bit daunting though.

Other than that, yep, XSLT is your friend.

Diez


== 3 of 3 ==
Date: Wed, Feb 17 2010 2:09 pm
From: John Bokma


Josh English <joshua.r.english@gmail.com> writes:

> I have several pages exported from a private MediaWiki that I need to
> convert to a PDF document, or an RTF document, or even a Word
> document.
>
> So far, the only Python module I have found that parses MediaWiki
> files is mwlib, which only runs on Unix, as far as I can tell. I'm
> working on Windows here.
>
> Has anyone heard of a module that parses wiki markup and transforms
> it? Or am I looking at XSLT?

One option might be to install a printer driver that prints to PDF and
just print the web pages.

Using Saxon or AltovaXML and a suitable stylesheet might give you the
nicest looking result though (but quite some work).

--
John Bokma j3b

Hacking & Hiking in Mexico - http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development

==============================================================================
TOPIC: mixins and new style classes
http://groups.google.com/group/comp.lang.python/t/5e9e7cabc90fed40?hl=en
==============================================================================

== 1 of 1 ==
Date: Wed, Feb 17 2010 12:31 pm
From: Bruno Desthuilliers


mk a écrit :
>>>> class Person(object):
> ... pass
> ...
>>>> class Friendly(object):
> ... def hello(self):
> ... print 'hello'
> ...
>>>>
>>>> Person.__bases__ += (Friendly,)
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: Cannot create a consistent method resolution
> order (MRO) for bases object, Friendly

Indeed. After the addition of Friendly to Person.__bases__, the mro for
Person would be (Person, object, Friendly). But the mro for Friendly is
(Friendly, object). This is not consistent. The right solution would be
to inject Friendly before object, ie:

Person.__bases__ = (Mixin, object)

Now the bad news is that this fails too:

TypeError: __bases__ assignment: 'Mixin' deallocator differs from 'object'

The above problem is not new, and had been discussed here:

http://bugs.python.org/issue672115

...and it's still unresolved AFAICT :-/

OTHO, the concrete use case for such a feature seem to be rather uncommon.

>
>
> But it works for old-style classes:

Old-style classes are a very different beast.


==============================================================================
TOPIC: The future of "frozen" types as the number of CPU cores increases
http://groups.google.com/group/comp.lang.python/t/7ef75c20d1be370d?hl=en
==============================================================================

== 1 of 1 ==
Date: Wed, Feb 17 2010 2:17 pm
From: "sjdevnull@yahoo.com"


On Feb 17, 2:35 am, Steven D'Aprano
<ste...@REMOVE.THIS.cybersource.com.au> wrote:
> On Tue, 16 Feb 2010 21:09:27 -0800, John Nagle wrote:
> >     Yes, we're now at the point where all the built-in mutable types
> > have "frozen" versions.  But we don't have that for objects.  It's
> > generally considered a good thing in language design to offer, for user
> > defined types, most of the functionality of built-in ones.
>
> It's not hard to build immutable user-defined types. Whether they're
> immutable enough is another story :)
>
> >>> class FrozenMeta(type):
>
> ...     def __new__(meta, classname, bases, classDict):
> ...         def __setattr__(*args):
> ...             raise TypeError("can't change immutable class")
> ...         classDict['__setattr__'] = __setattr__
> ...         classDict['__delattr__'] = __setattr__
> ...         return type.__new__(meta, classname, bases, classDict)
> ...
>
> >>> class Thingy(object):
>
> ...     __metaclass__ = FrozenMeta
> ...     def __init__(self, x):
> ...         self.__dict__['x'] = x
> ...
>
> >>> t = Thingy(45)
> >>> t.x
> 45
> >>> t.x = 42
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 4, in __setattr__
> TypeError: can't change immutable class
>
> It's a bit ad hoc, but it seems to work for me. Unfortunately there's no
> way to change __dict__ to a "write once, read many" dict.

Which makes it not really immutable, as does the relative ease of
using a normal setattr:

... t.__dict__['x'] = "foo"
... print t.x
foo
... object.__setattr__(t, "x", 42)
... print t.x
42

==============================================================================
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 3 ==
Date: Wed, Feb 17 2010 2:46 pm
From: Lawrence D'Oliveiro


In message <hlhdsi$2pn$1@theodyn.ncf.ca>, cjw wrote:

> Aren't lambda forms better described as function?

Is this a function?

lambda : None

What about this?

lambda : sys.stdout.write("hi there!\n")

== 2 of 3 ==
Date: Wed, Feb 17 2010 2:59 pm
From: Terry Reedy


On 2/17/2010 5:46 PM, Lawrence D'Oliveiro wrote:
> In message<hlhdsi$2pn$1@theodyn.ncf.ca>, cjw wrote:
>
>> Aren't lambda forms better described as function?
>
> Is this a function?
>
> lambda : None
>
> What about this?
>
> lambda : sys.stdout.write("hi there!\n")

To repeat: Python lambda expressions evaluate to function objects
identical, except for .__name__ attribute, to the equivalent def statememnt.

>>> type(lambda:None)
<class 'function'>
>>> import sys
>>> type(lambda : sys.stdout.write("hi there!\n"))
<class 'function'>

== 3 of 3 ==
Date: Wed, Feb 17 2010 3:17 pm
From: Ben Finney


Lawrence D'Oliveiro <ldo@geek-central.gen.new_zealand> writes:

> In message <hlhdsi$2pn$1@theodyn.ncf.ca>, cjw wrote:
>
> > Aren't lambda forms better described as function?
>
> Is this a function?
>
> lambda : None
>
> What about this?
>
> lambda : sys.stdout.write("hi there!\n")

They are both lambda forms in Python. As a Python expression, they
evaluate to (they "return") a function object.

--
\ "It is wrong to think that the task of physics is to find out |
`\ how nature *is*. Physics concerns what we can *say* about |
_o__) nature…" —Niels Bohr |
Ben Finney

==============================================================================
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: Wed, Feb 17 2010 3:37 pm
From: Imaginationworks


On Feb 17, 1:40 pm, Paul McGuire <pt...@austin.rr.com> wrote:
> On Feb 16, 5:48 pm, Imaginationworks <xiaju...@gmail.com> wrote:
>
> > Hi,
>
> > I am trying to read object information from a text file (approx.
> > 30,000 lines) with the following format, each line corresponds to a
> > line in the text file.  Currently, the whole file was read into a
> > string list using readlines(), then use for loop to search the "= {"
> > and "};" to determine the Object, SubObject,and SubSubObject.
>
> If you open(filename).read() this file into a variable named data, the
> following pyparsing parser will pick out your nested brace
> expressions:
>
> from pyparsing import *
>
> EQ,LBRACE,RBRACE,SEMI = map(Suppress,"={};")
> ident = Word(alphas, alphanums)
> contents = Forward()
> defn = Group(ident + EQ + Group(LBRACE + contents + RBRACE + SEMI))
>
> contents << ZeroOrMore(defn | ~(LBRACE|RBRACE) + Word(printables))
>
> results = defn.parseString(data)
>
> print results
>
> Prints:
>
> [
>  ['Object1',
>    ['...',
>     ['SubObject1',
>       ['....',
>         ['SubSubObject1',
>           ['...']
>         ]
>       ]
>     ],
>     ['SubObject2',
>       ['....',
>        ['SubSubObject21',
>          ['...']
>        ]
>       ]
>     ],
>     ['SubObjectN',
>       ['....',
>        ['SubSubObjectN',
>          ['...']
>        ]
>       ]
>     ]
>    ]
>  ]
> ]
>
> -- Paul

Wow, that is great! Thanks

==============================================================================
TOPIC: string to list when the contents is a list
http://groups.google.com/group/comp.lang.python/t/d604be2eee402ced?hl=en
==============================================================================

== 1 of 1 ==
Date: Wed, Feb 17 2010 3:48 pm
From: Wes James


I have been trying to create a list form a string. The string will be
a list (this is the contents will look like a list). i.e. "[]" or
"['a','b']"

The "[]" is simple since I can just check if value == "[]" then return []

But with "['a','b']" I have tried and get:

a="['a','b']"

b=a[1:-1].split(',')

returns

[ " 'a' "," 'b' " ]

when I want it to return ['a','b'].

How can I do this?

thx,

-wes

==============================================================================
TOPIC: error trying to join #python on irc.freenode.net
http://groups.google.com/group/comp.lang.python/t/6f73186707aafacb?hl=en
==============================================================================

== 1 of 2 ==
Date: Wed, Feb 17 2010 3:53 pm
From: Wes James


When I try to join #python on irc.freenode.net it keeps saying:

You need to identify with network services to join the room "#python"
on "irc.freenode.net".

Server Details:
Cannot join channel (+r) - you need to be identified with services

What does this mean?

thx,

-wes


== 2 of 2 ==
Date: Wed, Feb 17 2010 3:56 pm
From: Wes James


On Wed, Feb 17, 2010 at 4:53 PM, Wes James <comptekki@gmail.com> wrote:
> When I try to join #python on irc.freenode.net it keeps saying:
>
> You need to identify with network services to join the room "#python"
> on "irc.freenode.net".
>
> Server Details:
> Cannot join channel (+r) - you need to be identified with services
>
> What does this mean?


Nevermind, I think it means I need to register with the service and
supply real username/password.

-wes


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

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