Skip to main content

Ralsina.Me — Roberto Alsina's website

Python context managers: they are easy!

This comes from this thread in the Python Ar­genti­na mail­ing list (which I strong­ly rec­om­mend if you read span­ish).

I was the oth­er day try­ing to do shel­l-scrip­t-­like-things on python (as part of a mon­ster set­up.py) and I was an­noyed that in shell it's easy to do this:

cd foo
bar -baz
cd -

Or this:

pushd foo
bar -baz
popd

Or this:

(cd foo && bar -baz)

And on Python I had to do this, which is ver­bose and ug­ly:

cwd = os.getcwd()
try:
    os.chdir('foo')
    os.system('bar -baz')
finally:
    os.chdir(cwd)

This is what I want­ed to have:

with os.chdir('foo'):
    os.system('bar -baz')

And of course, you can't do that. So, I asked, how do you im­ple­ment that con­text man­ager? I got sev­er­al an­swer­s.

  1. That's avail­able in Fab­ric:

    with   cd("foo"):        run("bar")  
  2. It's not hard to do:

    class   DirCon­textM(ob­ject):        def   __init__(self,   new_dir):            self.new_dir   =   new_dir            self.old_dir   =   None          def   __en­ter__(self):            self.old_dir   =   os.getcwd()            os.chdir(self.new_dir)          def   __ex­it__(self,   *_):            os.chdir(self.old_dir)  
  3. It's even eas­i­er to do:

    from   con­textlib   im­port   con­textman­ag­er    @con­textman­ag­er  def   cd(path):        old_dir   =   os.getcwd()        os.chdir(path)        yield        os.chdir(old_dir)  
  4. That's cool, so let's add it to path.py

  5. Maybe check for ex­­cep­­tions

    @con­textman­ag­er  def   cd(path):        old_dir   =   os.getcwd()        os.chdir(path)        try:            yield        fi­nal­ly:            os.chdir(old_dir)  

All in al­l, I learned how to do con­text man­ager­s, about con­textlib, about fab­ric and about path.py. Which is not bad for 15 min­utes :-)

Book review: The Windup Girl by Paolo Bacigalupi

I start­ed this book with high hopes. Af­ter al­l, this was a book by a new-ish au­thor that had won Hugo Award for Best Nov­el (2010), Neb­u­la Award for Best Nov­el (2009), Lo­cus Award for Best First Nov­el (2010), John W. Camp­bell Memo­ri­al Award (2010), Comp­ton Crook Award (2010) Comp­ton Crook Award (2010), Goodreads Choice Award Nom­i­nee for Sci­ence Fic­tion (2009). Im­pres­sive, uh?

Well, I don't know what they saw in it. Shal­low char­ac­ter­s, per­va­sive fa­tal­ism dis­guised as depth, mprob­a­ble slang ust be­cause it sounds cool (windup girl? Re­al­ly? That's how they will call ge­net­i­cal­ly en­gi­neered hu­mans in the fu­ture? Windup­s? Yeah, right).

Oh, and it's full of ori­en­tal­is­m. And of things like im­plant­ing gene dogs in­to windups to make them loy­al and sub­servien­t. And ghost­s. Oh, crap, al­most noth­ing in this nov­el worked for me. Most pages had me slap­ping my­self on the fore­head.

I am­not against a sol­id dose of weird. I like weird. I read Miéville, for crap's sake. But this is not weird, it's con­trived.

And don't get me start­ed on the end. The end is such an ob­vi­ous anal­o­gy to Eden it al­most made me puke. It's like the end of Bat­tlestar Galac­ti­ca, but set on the fu­ture. And with la­dy­boys.

I had a bet­ter time read­ing H. Rid­er Hag­gard's "Al­lan Quater­main", which I saw men­tioned in the awe­some se­ries "The vic­to­ri­an Hugos". Old and dat­ed? Sure. But I would vote for it in­stead of "The Windup Girl" ev­ery day, and twice if they let me.

That's Math! I Know Math! (No I don't)

The ti­tle is a quote from Juras­sic Park, if you were won­der­ing. A girl, chased by di­nosaurs, runs in­to a com­put­er, no­tices it's Unix, says "That's Unix! I know Unix!", and pro­ceeds to hack some­thing or oth­er that lets her es­cape the pre­vi­ous­ly men­tioned di­nosaurs.

Well, that's how life of­ten feels for me, ex­cept with Math. And with­out di­nosaurs. I am sur­round­ed by trou­ble, some­thing is com­plete­ly bro­ken in a way I can't quite get, things feel just slight­ly weird... and sud­den­ly... that's math! I know math! (of course I don't know math, noone knows math. We all just know some math­).

I may see an ad and no­tice the huge dis­count is just a clev­er­ly dis­guised tiny dis­coun­t. A snip­pet of news may re­veal it­self as com­plete non­sense af­ter a cur­so­ry anal­y­sis. A for­ward­ed mail may be­come slight­ly more an­noy­ing be­cause of its ob­vi­ous stu­pid­i­ty. Be­cause of math.

Math is the tool I have to make sense of things. When the world gets con­fus­ing and scary, if it can be ex­pressed in num­ber­s, it calms me down. Afraid of the fu­ture? Let's con­sid­er the won­ders of com­pound in­ter­est. Scared of death? Well, look at prob­a­bil­i­ties. Need­ing a lit­tle ad­ven­ture? Well, there is game the­o­ry! Need a con­ver­sa­tion starter? You can men­tion you once spent time in class fig­ur­ing out the ho­meo­mor­phism that ex­plains the scene in Flash­dance where the welder re­moves her bra through her sleeve.

Math tells me the world is not per­fec­t. Math tells me the num­bers I see on my com­put­er are not re­al­ly re­al num­ber­s, and can't be trust­ed. Math tells me I can't cross all the bridges in Könis­gerg on­ly once. Math tells me the num­ber one is the most fre­quent num­ber in to­day's pa­per. Math tells me Pla­to was right and there is a uni­verse of pure ideas, and this is but a re­flec­tion.

On the oth­er hand, Math tells me I can cut an or­ange in­to a few pieces, which re­assem­ble in­to two, iden­ti­cal, or­anges. So take what she says with a grain of salt.

Coffee and I

One of the most vivid mem­o­ries of my late child­hood was when my fa­ther fi­nal­ly let me to stay at his ta­ble in the Gran Do­ria café, when it was still lo­cat­ed in the dark bow­els of a galería in San­ta Fe's San Martín street.

I was maybe 12, and I had seen him sit there with a cor­ta­do while my moth­er went shop­ping with us, or while I went to one of those things kids go to (artis­tic ex­pres­sion class­es? Pup­petry work­shop?) and it was such a mis­tery. It was like a three hour hole in my dad's life of which I had no in­for­ma­tion.

What would he do there? Who did he talk to? Did he read some­thing? And al­ways there, at the ta­ble when I came back was an emp­ty small cor­ta­do cup.

I sus­pect that's when I start­ed lik­ing the idea of cof­fee. I was, of course, an in­vet­er­ate hot choco­late drinker (El Quil­lá brand, un­known be­yond that city, yet su­pe­ri­or in my mind to any oth­er­s), af­ter a long, long time of drink­ing warm sweet­ened milk. And I know I had tried cof­fee be­fore and hat­ed it, but of course, sit­ting there, I said "un cor­ta­do, por fa­vor". And boy was that thing aw­ful. I did not drink cof­fee again for twen­ty years.

I did learn to like tea, or at least tea with milk, and learned, in col­lege, to drink mate like a sponge. Bit­ter and strong as hel­l, the clos­est caf­feine de­liv­ery mech­a­nism to an IV drip, slow, weak and con­stant over hours. You have not re­al­ly been awake un­til it's 5 AM, you are on your third ther­mos, and it feels like 2P­M. It's like the wrong kind of pill in the Ma­trix.

But then I moved to Buenos Aires and I was alone. And drink­ing mate alone is like drink­ing Vod­ka alone, de­press­ing and dirty, so I start­ed go­ing to cafés and or­der­ing lá­gri­mas. A lá­gri­ma es like a back­wards cor­ta­do. If you get a big cup and put a lá­gri­ma and a cor­ta­do in it you will get a de­cent café con leche. It's a pa­thet­ic bev­er­age, on­ly fit for the emo­tion­al wreck I was at the time.

But it's a gate­way drink. And by 2002 I was drink­ing cor­ta­dos. And by 2006 I had my own espres­so ma­chine and was some sort of caf­feine Kei­th Richard­s, do­ing maybe 10 strong cups a day, buy­ing ex­pen­sive blend­s... and then I had to stop.

On Jan­u­ary 1st 2008 I woke up at 4AM with in­tense chest pain. I thought I was hav­ing a heart at­tack. I walked to the hos­pi­tal and it turned out to be gas­tri­tis. This hap­pened again. And again. Not of­ten, but once ev­ery year, then ev­ery six month­s, then ev­ery mon­th, then four days in a row. And I had to give up cof­fee.

It was hel­l. I was asleep all day and awake all night, not hav­ing my crutch to mod­u­late my sleep. I was grouchy, and an­noy­ing. I cheat­ed. But then I stopped.

Sor­ry dad.

The death penalty and other conspiracies.

Ev­ery once in a while, some­thing aw­ful hap­pen­s. And then some­one will say "the peo­ple who do that should get the death penal­ty". In­vari­ably, that is a stupid ar­gu­men­t.

Let's start by dis­pos­ing of the ob­vi­ous low blow: "if it hap­pened to your son, you would ask for their death too". To which the ob­vi­ous an­swer is, of course I would. And I would be push­ing for a stupid so­lu­tion to the prob­lem.

If some­thing re­al­ly, re­al­ly bad hap­pened to my son, I would be suf­fer­ing, and in a state of vi­o­lent emo­tion and dis­tress. If I told you to jump off a bridge, would you? I guess not, be­cause you would no­tice I am at the edge of mad­ness and just told you that be­cause I am feel­ing that way.

Well, the same is true about a vic­tim's rel­a­tives (or the vic­tim him­self) ask­ing for a spe­cif­ic pun­ish­men­t: it's a re­quest born from pain and suf­fer­ing. And as a so­ci­ety, we should not de­cide our ac­tions based on te pro­pos­als of the ones al­most in­sane with grief. Be­cause we want to take the ac­tion that is bet­ter for so­ci­ety, not for a spe­cif­ic mem­ber of it. So, for­get about that ap­peal to sen­ti­men­t, be­cause while com­plete­ly un­der­stand­able, it is stupid, be­cause those griev­ing are al­lowed to be stupid.

An­oth­er failed ar­gu­ment for the death penal­ty is that it dis­cour­ages fu­ture crime. This has been shown not to be the case, be­cause sim­i­lar coun­tries or states with and with­out death penal­ty show no sig­nif­i­cant dif­fer­ence on crime rates.

I sus­pect this is be­cause in many cas­es the crim­i­nal does­n't in­tend to ac­tu­al­ly com­mit the part of the crime that brings the death sen­tence (mur­der when rob­bing? The crim­i­nal want­ed to rob, not to mur­der) or he just would do it any­way (it's not as if child rapists ex­pect to have a nice time when cap­tured. They just do it as­sum­ing they won't get caugh­t, or de­cide it's worth it any­way).

And of course, the main rea­son why the death penal­ty is a bad idea is that it would be ap­plied by pub­lic em­ploy­ees. Do you trust the gov­ern­ment to de­cide how much to charge you in tax­es? No, you do it your­self, with an ac­coun­tan­t, and tell them how much to take. Do you ex­pect the po­lice to find a wal­let you dropped on the street? Do you trust the gov­ern­men­t's mail with re­al­ly im­por­tant pack­ages? Are you con­fi­dent about the gov­ern­ment fig­ur­ing out all en­vi­ron­men­tal is­sues? Well, then why would you trust them to kill any­one they de­cide is a re­al­ly, re­al­ly bad guy?

The gov­ern­ment is a great idea for things noone else wants to do (high­ways), or things noone else should be do­ing (law en­force­men­t) but even in those cas­es you must al­low for them pro­vid­ing a crap­py ser­vice, and care­ful­ly use your in­put to lim­it what they can do.

The al­ter­na­tive is to as­sume that the gov­ern­ment has a huge ca­pa­bil­i­ty and com­pe­tence but has just de­cid­ed not to show it, which is per­haps the most amaz­ing part of most con­spir­a­cy the­o­ries.

The US gov­ern­ment can't kill Cas­tro, but can kill Kennedy. A gov­ern­ment can't keep the trains run­ning, but can fake a moon land­ing. And so on, and so forth.

I once read a book where they de­scribed an in­ter­est­ing sci­ence: Con­spir­a­cy The­o­ry The­o­ry. It's the sci­ence of study­ing what con­spir­a­cy the­o­ries peo­ple be­lieve in, to get in­sight in­to what they ac­tu­al­ly be­lieve. If you are in favour of the death penal­ty, then you be­lieve law en­force­ment does­n't make mis­takes, or that killing a few ran­dom peo­ple ev­ery now and then (be­cause they make mis­takes) is not a prob­lem. If the first, you are stupid, if the sec­ond, you are evil.


Contents © 2000-2024 Roberto Alsina