Friday, April 25, 2014

Python variables can have types as values

By Vasudev Ram



I came across this article by Peter Norvig:

Design Patterns in Dynamic Languages

(Peter Norvig is Director of Search at Google and a highly accomplished computer scientist.)

Haven't read the article fully yet, but scanned it a bit, and one line in particular interested me:

"A variable can have a type as a value"

That line is on the page with the heading: "First-Class Dynamic Types"

So I thought of checking this in Python - that section of the article seems to be about Lisp and Dylan (the programming language)).

Here's some code I used to check whether Python variables can have types as values - I typed it in the Python interpreter, so both the input and the output appear below:
>>> a = int
>>> type(a)
<type 'type'>
>>> print a('3') + 4
7
>>> b = str
>>> print b(12) * 5
1212121212
>>> class Foo:
...     def bar(self):
...         print "in Foo.bar()"
...
>>> f = Foo
>>> f().bar()
in Foo.bar()
>>>
And here's a couple more lines which give a clue why the above works:
>>> id(int)
505548800
>>> id(a)
505548800
>>> id(str)
505571224
>>> id(b)
505571224
Note that the names int and str have valid id()s, and that id(a) == id(int), and id(b) == id(str).

So it seems that variables in Python can have values that are types. Of course, the id() stuff I did above indicates that it will work for all Python types if it works for one, since "a = int" binds the name a to the same object that the (built-in) name int is bound to. That's my guess, anyway. Interested to see if anyone has any different ideas or a better explanation.

And speaking of Peter Norvig, here's another article by him about Albert Einstein:

'05 Annual Performance Review: Albert Einstein

- Vasudev Ram - Dancing Bison Enterprises

Contact Page

2 comments:

Vasudev Ram said...

Oops, that was a typo. In the line:

Peter Norvig is Director of Search at Google

It should actually be Director of Research. (He was earlier Director of Search Quality.)

Maybe it's an appropriate typo, though; just add the re :-)

thomasmappbe said...

thanks