[Chicago] Metaprogramming Puzzles

Thomas Johnson thomas.j.johnson at gmail.com
Sun Oct 5 02:16:18 CEST 2014


I've actually used metaprogramming a couple of times for improving speed in
python. In one case, I had a list of ranges like [[123, 456], [314, 1592],
...]. My program had to check if a given number was within any of the
ranges. It called this check function tens of millions of times, and it
consumed a large fraction of the total program runtime.

My first try at improving the speed was to use interval trees as
implemented in the Python's banyan module. This gave a significant
improvement, but the function was still slowing the program down.

This lead me to metaprogramming: At the beginning of the program, I
generated a function by dynamically writing a series of Python if/then
statements (along with the def() boilerplate) to a string, and then exec'd
the string to create the function. So for the list above, the string would
look like "def check(x):\n if x>=123 and x<=456:\n return True..." This was
way faster than the banyan implementation, and after using this technique
the function runtime became negligible.


On Sat, Oct 4, 2014 at 6:27 PM, Brantley Harris <deadwisdom at gmail.com>
wrote:

> Meta programming is very important to learn. Play with it, understand it.
> But never use it on a real project unless you absolutely have to. It's like
> a nuclear bomb, the last resort.
>
> I wrote a fun little class a while back that was named "continued". So you
> could continue defining a class after it was already made. As an excercise,
> make this work:
>
> class A(object):
>     def foo(self):
>         return self.bar()
>
> class A(continued):
>     def bar(self):
>          print "foo bar!"
>
> > a = A()
> > a.foo()
> foo bar!
>
> And then once you make this, never use it.
>
> On Saturday, October 4, 2014, Jason Wirth <wirth.jason at gmail.com> wrote:
>
>> Hey Chipy~
>>
>> Does anyone have a good metaprogramming puzzle?
>>
>> I've never gotten very into metaprogramming due to the old saying, "if
>> you think you need metaprogramming, you're probably doing it wrong."
>> However, lately I've become more curious about metaprogramming,
>> understanding how it could be useful, and learning the deeper workings of
>> Python.
>>
>> There are a lot of books and online tutorials, but I find them boring and
>> lacking in application. Rather than reading a guide, I would like to learn
>> by trying to solve puzzles. Anyone have any good metaprogramming puzzles?
>>
>>
>> --
>> Jason Wirth
>>      213.986.5809
>>     wirth.jason at gmail.com
>>
>
> _______________________________________________
> Chicago mailing list
> Chicago at python.org
> https://mail.python.org/mailman/listinfo/chicago
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/chicago/attachments/20141004/1a1ef5fc/attachment.html>


More information about the Chicago mailing list