Monday, November 24, 2008

python typecheck with decorators

yesterday i was thinking on the alternative to the exceptions.

like, you know, something that would safely propagate through functions without having to wrap up every damn function call in try-except block, allowing only topmost code to react on errors.

what i had in mind was something like Maybe monad in Haskell, where function could return a value, or nothing, and that would get accepted as a correct return value by other operators or functions.

of course, that would require adding Haskell type system to python :)

speaking of which, i found the idea of type checking really interesting, so i came up with this dynamic type check decorator. i think it's a nice step forward towards correct code. easy on eyes, small, allows custom error handling and reporting.


# exmaple of checking inputs and output of a function
def signature(*types):
def check_inputs(f):

acc_types = types[:-1]
ret_type = types[-1]

assert len(acc_types) == f.func_code.co_argcount

def new_f(*args, **kwds):
for (a, t) in zip(args[:-1], acc_types):
assert isinstance(a, t), \
"arg %r does not match %s" % (a,t)

result = f(*args, **kwds)
assert isinstance(result, ret_type), \
"return value %r does not match %s" % (result,ret_type)

return result

new_f.func_name = f.func_name
return new_f

return check_inputs

# last argument is a type of the return value
@signature(int, int, list, bool, str)
def report(a,b,c,d):
number = a+b+sum(c)

if d == False:
return str(False)

return str(number)

print report(1,2,[1,2,3],False)

Monday, July 28, 2008

php considered immature

so i'm writing this mailing sender in php. test driven design works btw. just need to get used to it. anyway, over a week i ran into 3 behaviors, that really made me scratc hmy head a bit:

1) i installed Pear::Mail, and skipped dependencies. "well", i thought, "it'll tell me if i'll need any". so i'm creating html emails, building whole test suite, code, class etc. everything works except one minor detail. when it should actually send email - it does nothing. silently exit, without sending. no errors, nothing. turns out - it needed Pear::Mail#net_smtp. took me some hours to figure out.

2) the plan was to spawn a process with proc_open(), send info to it through pipe and get an output from pipe. easy, right? but! what happens, if the process hangs? just poke it until predefined timeout occurs. yeah, not that easy. turns out proc_open() pipes can't be set to non-blocking, meaning if parent tries to read from process and process hangs - parent hangs as well. now i have to use shared memory or whatever, just because those pipes can't be set to non-blocking.

3) the script had 3 include files and was spawned by parent script. when parent was run from command line - all went ok. when parent was called from apache - it didn't do what expected. after some poking i figured out, that it didn't return from the second include. nope. just entered it, ran through it and exited, never returning to parent to include third script and, actually, do what's needed. this one really took some time. turned out - it was whitespace, after the ending tag "?>". how on earth would that be relevant? no idea. but it worked from webserver then, as well.

three different bad behaviors, over the course of a week. talk about language maturity.

Friday, June 27, 2008

productivity

last 2 weeks i was working on a project started anew, so i decided to make a short summary on it. the only metric i could think of is LOC, so i went with it. here we go, numbers represent lines/words/characters in each dir:

classes 665 1857 20334

js 228 469 6586

config 18 45 625

templates 336 688 10849

views 390 746 9295

css 216 368 3398

unittests 498 1293 15338

total:
php: 1073
templates: 336
js: 228
css: 216
unittests: 498

grand total: 2351
time: 2 weeks ~ 40*2 = 80 hours
productivity: 2351/80 = 29.39 lines per hour

so the productivity is very close to standard 30 lines/hour. guess i'm doing okay :)

Sunday, June 22, 2008

smalltalk

wow, that's one cool explanation on class methods :)

When you create a class, Smalltalk creates a metaclass; and just like a class describes how methods for its instances work, a metaclass describes how class methods for that same class work.

Set is an instance of the metaclass, so when you invoke the #new class method, you can also say you are invoking an instance method implemented by Set class. Simply put, class methods are a lie: they're simply [metaclass] instance methods that are understood by instances of metaclasses.

Friday, June 6, 2008

another job well done!

phew, finished the haskell book. solid stuff. will be looking to do some projects in it(parser? compiler?).

moving to flex meanwhile. need to check what it's all about. ecmascript is kinda fun - dynamic, prototyped language. too bad that i suck at design :)

Wednesday, June 4, 2008

haskell power!

i'm still reading a book on haskell - "Haskell - The Craft of Functional Programming".

nice introductory and overall stuff.

so, haskell have a lot of high level functions(what a surprise for a functional programming language!), today two of them impressed me.

1) iterate: "creates an infinite list where the first item is calculated by applying the function on the secod argument, the second item by applying the function on the previous result and so on".

Input: take 10 (iterate (2*) 1)

[1,2,4,8,16,32,64,128,256,512] ('take' takes first n items of a list)

so it takes an argument as a starting point and continues applying function to it.

it can take lambda functions, like this:

Input: take 10 (iterate (\x -> (x+3)*2) 1)

[1,8,22,50,106,218,442,890,1786,3578]

and i thought that this can be used to calculate fibonacci numbers!

take 10 (iterate (\(x,y)->(y,x+y)) (1,1))

[(1,1),(1,2),(2,3),(3,5),(5,8),(8,13),(13,21),(21,34),(34,55),(55,89)]

2) list comprehensions. not exactly a function, but very nice construct. they may return infinite lists.

it should be pretty much familiar to python programmers, though more powerful.

[ f x | p1, p2, p3... ]

each value can be transformed by function f
p1, p2... - conditions that evaluate to boolean OR generators

"so what" you may say, nothing new. yeah, except p1, p2... can use values from generators on the left!

e.g., we can have a infinite list of pythagorean triples:

[ (x,y,z) | z <- [2..], y <- [2..z-1], x <- [2..y-1], x^2 + y^2 == z^2 ]

[(3,4,5),(6,8,10),(5,12,13),(9,12,15),(8,15,17),(12,16,20),(15,20,25),(7,24,25),(10,24,26),(20,21,29)]

i was really excited about those two. enough to blog about 'em :)

Sunday, February 10, 2008

lisp and smalltalk

so i finally finished the SICP book. haven't done most of examples, skimmed through some contents on compilers, but still! man, what a piece of art.

just as brooks'"mythical man-year" being a great summary of engineering experience, this one is a great summary of computer science concepts.

i think any programmer should read it to become a better one. especially those without functional programming experience. just blows your mind :)

so i decided to put FP aside for a while and concentrate on imperative PLs, especially since i have a nice big several months project coming up on python/django.

so - smalltalk. designed for children. pure OO. i just started on "smalltalk by example" by alex sharp.

nice stuff. OO examples, design philosophies and best practices are pretty universal. python borrowed alot from smalltalk, really.

but there are some quirks. here you go:"Besides class variables and instance variables, Smalltalk provides a variable called a class instance variable.
It's a variable defined on the class side, and provides a way to hold a value that is potentially different for each
subclass of the original class. Instances of each subclass all have access to the variable, but instances of one
subclass will see a different value than will instances of another subclass."

Thursday, January 17, 2008

fun

в качестве тестового задания надо пропатчить babel! вот это я понимаю - подход! :)

Sunday, January 6, 2008

lisp vs haskell

okay, i started reading on haskell when i'm not reading SICP. haskell is also functional PL, so i'm not really losing focus alternating them. so second basic data structure in haskell is tuple(first being list, of course). it's an immutable set of object with the same type(types do play a major role in HS).

and tuple of 2 elements(pair) is of different type, than tuple of 3(triple) or more elements. there's a shortcut to get values from pair fst(1,2) == 1, snd(1,2) == 2.

but guess what, they ain't workin' on tuples of other sizes! not sure i'm following the logic of HS creators yet :)

so why i mentioned lisp - it's main data structure is list(no surprises, it's called LISt Processing after all). lists there are actually "linked lists", first element can be accessed as "car(list)", and rest of the list is "cdr(list)". so "car(cdr(list))" is a second element of the list. there's even a shortcut for it - "cadr".

and you can stuff any number of "a"'s or "d"'s there, to get the needed element(or list tail), "cdddr(list)" is "all list elements starting from fourth".

no limitations for lists of size 2! :)

Thursday, January 3, 2008

smalltalk

was reading an article about lisp and smalltalk, describing them as language of gods. i know a bit of lisp, reading my second book on it atm(structure and interpretation of computer programs), and i can imagine it being an ancestor of all the functional PL out there.

so smalltalk should be it's OO counterpart. so i went to read a wiki article on it and it's a *WOW* stuff. it's all been there for over 30 years. i mean - everything's an object, message passing, code blocks(hello python list comprehensions), temp variables(now that's where ruby got its |x| down the pipe), docstrings(easy one)!

there's a web framework written in smalltalk - seaside, so i think after finishing SICP i'll give them both a try.

next in the list of languages to dive into - haskell.