14May

Python can be just as ugly as PHP…

Posted by Elf Sternberg as PHP, python

I was reading through the WordPress source code, trying to figure out a problem for a contractor, when I saw the function compact().  When I saw it I boggled, read the description, and shook my head.

Compact() takes a list of variable names as strings, and returns a hash of those variable names and their values.   So if you have something like:

$title = "My blog";
$link = "foo";
$h = compact('title', 'link');

You get back a hash of array('title' => 'My blog', 'link' => 'foo').

That, to my thinking, is completely messed up.  You’re giving this function, which has its own scope, explicit permission to twiddle with variables in the current scope and create a new variable.  It’s one of those things that convinces me that PHP is an unholy mess of silliness.

And then my brain reminded me that, hey, you can do the exact same thing in python.  So, I have:

import inspect
def compact(*args):
    return dict([(i, inspect.currentframe().f_back.f_locals.get(i, None)) 
                 for i in args])

def foo():
    a = "blargh"
    b = "bleah"
    c = ['1', '2', '3']
    return compact('a', 'b', 'c')

print foo()

And sure enough, this spits out: {'a': 'blargh', 'c': ['1', '2', '3'], 'b': 'bleah'}

I hang my head in shame for giving Django developers one more thing around which they can develop bad habits.

1 Response to Python can be just as ugly as PHP…

Python:Python equivalent of PHP's compact() and extract() – IT Sprite

October 29th, 2015 at 11:42 am

[…] I’ve written more extensively about this: Python can be just as ugly as PHP. […]

Comment Form

Subscribe to Feed

Categories

Calendar

May 2009
M T W T F S S
« Apr   Jun »
 123
45678910
11121314151617
18192021222324
25262728293031