late bindings ???

Christopher A. Craig list-python at ccraig.org
Mon Dec 2 09:47:28 EST 2002


"Alfredo P. Ricafort" <alpot at mylinuxsite.com> writes:

> Now, I am looking for something that can 'typecast' a variable into a
> function. But it appears that there is none. It seems that in python
> late bindings are not allowed.

This question has nothing to do with late bindings or typecasting.
I'll deal with that first:

Python actually has nothing but late bindings.  Early binding means
that (as in C++) I can figure out what function is called at compile
time and if I want to inline the code (and I certainly can hard code
the jump), and generally only occurs in statically typed languages.  In
Python bindings are always done at run time.  If I do the literal 4+6
then every current implementation I know will lookup up the type of 4
(an int) and the addition method associated with it (the
PyInt_Type->tp_as_number->nb_add method) and run that.  This adds a
large degree of flexibility, but also adds a couple layers of
indirection that can lead to slow execution.  To say this more simply,
if I write a function

def t(a, b):
  return a+b

I cannot know at compile time what function the '+' operator called,
it must be bound at run time (late).  

As for typecasting (which is very hairy in Python because Python is
strongly typed) it wouldn't help either.  If I change the type of the
string "do_func" to be a function (which I could do in C or C++) I
would get complete gibberish if I called it (most likely a segfault).
Casting won't change the value of a variable, only its type.  So I
still have the seven bytes "do_func" stored in the location, but I'm
treating it as a function instead of a string.

What you want to do is a very, very bad idea that should be avoided at
all costs, but Python can do it:

Python 2.2.1 (#4, Sep 26 2002, 16:06:41) 
[GCC 3.1] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> t = ['funca', 'funcb']
>>> def funca(*l, **d):  
...   print l
... 
>>> eval('apply(%s, %s)' % (t[0], [1, 2]))
(1, 2)


-- 
Christopher A. Craig <list-python at ccraig.org>
"Never let schooling get in the way of your education"  Mark Twain




More information about the Python-list mailing list