Determining types of variables and function params by parsing the source code

Markus Meyer meyer at
Fri Aug 23 17:14:56 CEST 2002


I have been playing around with Python for a while and personally, I
find, one of the biggest strengths is that one doesn't have to declare
variable types actually, and I strongly believe any RAD tool shouldn't
require you to mess with types explicitely. Unfortunately this limits
the knowledge about the types at the edit/compile time, and that f.e
leads to the fact that most auto-completion in Python editors is weak.

To (partially) overcome this I wonder if the following would be

Variables (objects) are instantiated in Python by using one of the
following mechanisms (am I missing something?):
1) Explicit instantion of basic types (numbers, strings, ...)
2) Construction by the object constructor
3) Assignment of another variable
4) Assignment of the return value of a function
5) Assignment of the result of an operator action (f.e. list

What I intend to do is to "trace forward" these assignments to obtain
as much type information as possible. Imagine the following code:

"this is"
def print13(s):
   t = s[1:3]
   print t

s = 'hello'

The following informaton could be extracted by a sophisticated parser:
- print13 takes an argument of type string (because it is called with
argument s, which is a string because of the previous assignment)
- print takes an argument of type string (because it is called with
argument t, which was constructed by using the [] operator on s, which
is an argument of the function print13, which takes an argument of
type string)

Of course I'm aware that there is inheritation, and some function can
take arguments of more than one type. One would have to take this into

Further extensions would be possible. F.e., if you have some context
where var.myspecialfunc() is called, and MySpecialClass is the only
class declaring a public function with name myspecialfunc(), you can
safely assume, that var is of type MySpecialClass.

So, is this total crap? Has anyone else tried this? If not, would you
recommend writing (1) another parser for Python, (2) use the parser
module, (3) do something completely different?

Looking forward to read from you.


More information about the Python-list mailing list