Kelketek
Kelketek

Reputation: 2446

Get symbol for def in module in Python

I'm writing an interpreter for an old in-game scripting language, and so need to compile dictionary that has the name of the command from the language matched up against the symbol for that function.

Now, I've already figured out here: How to call a function based on list entry?

...That you can call functions this way, and I know that you can use dir to get a list of strings of all functions in a module. I've been able to get this list, and using a regex, removed the built-in commands and anything else I don't actually want the script to be able to call. The goal is to sandbox here. :)

Now that I have the list of items that are defined in the module, I need to get the symbol for each definition.

For a more visual representation, this is the test module I want to get the symbol for:

    def notify(stack,mufenv):
        print stack[-1]

It's pulled in via an init script, and I am able to get the notify function's name in a list using:

    import mufprims
    import re

    moddefs=dir(mufprims)
    primsfilter=re.compile('__.+__')
    primslist=[ 'mufprims.' + x for x in dir(mufprims) if not primsfilter.match(x) ]
    print primslist

This returns:

    ['mufprims.notify']

...which is the exact name of the function I wish to find the symbol for. I read over http://docs.python.org/library/symtable.html here, but I'm not sure I understand it. I think this is the key to what I want, but I didn't see an example that I could understand. Any ideas how I would get the symbol for the functions I've pulled from the list?

Upvotes: 0

Views: 1989

Answers (2)

jdi
jdi

Reputation: 92617

I thought I might add another possible suggestion for retrieving the functions of an object:

import inspect

# example using os.path
import os.path
results = inspect.getmembers(os.path, inspect.isroutine)

print results

# truncated result
[...,
('splitdrive', <function splitdrive at 0x1002bcb18>), 
('splitext', <function splitext at 0x1002bcb90>), 
('walk', <function walk at 0x1002bda28>)]

Using dir on the object would essentially give you every member of that object, including non-callable attributes, etc. You could use the inspect module to get a more controlled return type.

Upvotes: 2

Sam Dolan
Sam Dolan

Reputation: 32532

You want to get the function from the mufprims module by using getattr and the function name. Like so:

primslist=[getattr(mufprims, x) for x in dir(mufprims) if not primsfilter.match(x) ]

Upvotes: 2

Related Questions