Sometimes, I like tweeting in code instead of plain words. So I tweeted this:
exec('class Me:\n def drink_beer(self): self.has_headache = True') ; me = Me() ; me.drink_beer() ; print me.has_headache #BEER
exec is a statement not a function1.
I had tried to use eval() first but it only accepts expression so exec seems to be right one to use because it accepts statement, well you can feed it with a entire source file actually. If we just give our code, then the code will be executed in current scope.
I do this is because I need to have one-liner code, you dont have \n or <br/> on Twitter3, I just wrote it for fun. If you want to use eval() or exec in real program, you must use them with care.
[1] | This would work because a tuple with only one element is not a tuple but the element unless you append with , after that only element2. So it is evaluated like exec only_element. |
[2] | A single item tuple must have a trailing comma, such as (d,), from documentation. |
[3] | Actually it has \n but you have to go to HTML source code, atom feed, or json via API. In the representation of HTML, \n doesnt give your line break. |