[Tutor] call a def/class by reference

Michael Sparks zathras at thwackety.com
Fri Sep 30 00:58:33 CEST 2005


On Thursday 29 September 2005 22:26, Alan G wrote:
> string -> function mapping directly.
>
> Its not usually a very useful thing to do

This is precisely how shared libraries under linux and IIRC DLLs in windows 
work. cf dlopen, dysym in C. 

> how would the typical user know what the function names were?

Under linux one can examine the names of functions in a library using "nm".

eg:
# nm libpython2.4.so|head -20
         U abort@@GLIBC_2.0
000dfea0 d abs_doc
0001fcf0 t abstract_get_bases
0001fe20 t abstract_issubclass
         U access@@GLIBC_2.0
000e9ba0 d acquire_doc
0008f970 t addcleanup
0001be40 t addclosure
000d2040 d add_doc
0009d7c0 t add_flag
0001b8f0 t addnfaarc
0001b870 t addnfastate
00059680 t add_subclass
00049de0 t adjust_tp_compare
000ea680 d alarm_doc
         U alarm@@GLIBC_2.0
000e9760 d allocate_doc
000e6280 d api_version_warning
0003a6f0 t app1
000cfc40 d append_doc

Obviously, ctypes does much the same thing. 

Compare and contrast:

try: 	 
    from ctypes import * 	 
    libc = cdll.LoadLibrary("/lib/libc.so.6") 	 
    sched_yield = libc.sched_yield
 except ImportError: 	 
    def sched_yield(): pass
 except AttributeError:
    def sched_yield(): pass

with ...

try:
   import functions as libc
   sched_yield = getattr(libc, "sched_yield")
                               # this is of course effectively equivalent to:
                               #   sched_yield = libc.sched_yield
except ImportError:
    def sched_yield(): pass
except AttributeError:
    def sched_yield(): pass

It's pretty much the same thing. I could see that this may have uses in 
systems that allow plugins.

Devils-advocate-ly , ;-)


Michael.



More information about the Tutor mailing list