Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alias all methods from an object?

I'm creating a script that's actually an environment for other users to write code on.

I've declared several methods in a class and instantiate an object so users can use those methods as simple interpreter functions, like so:

from code import interact

class framework:
    def method1(self, arg1):
    # code for method1
    def method2(self, arg2):
    # code for method2

def main():
    fw = framework()

    # Aliases
    method1 = fw.method1
    method2 = fw.method2

    interact(local=locals())

Since I don't want the user to call the methods with fw.method1(arg), I setup aliases. The problem is, since the framework class is under development, I have to keep updating the main script with new aliases for the methods I create.

Is there a simple way of getting rid of the "fw." part on the calls and have all the methods under class framework automatically visible under main?

like image 347
Andrei Avatar asked Mar 28 '19 14:03

Andrei


2 Answers

You control the dictionary passed to interact, so put what you want in it without worrying with local variables in main:

d={}
for n in vars(framework):
  if n.startswith('_'): continue  # probably
  x=getattr(fw,n)
  if callable(x): d[n]=x
interact(local=d)

This works for regular, static, and class methods. It doesn’t see instance attributes (unless they’re shadowing a class attribute) or inherited methods.

The former matters only if the instance stores functions as attributes (in which case you might or might not want them available). The latter is convenient in that it omits object; if there are other base classes, they can easily be included by searching framework.__mro__ (and still omitting object).

like image 97
Davis Herring Avatar answered Oct 17 '22 19:10

Davis Herring


I don't know what you plan to do with the functions, but if they are not static it will not likely work outside of the class:

fs = [func for func in dir(c) if callable(getattr(c, func)) and not func.startswith("__")]
for func in fs:
    globals()[func] = getattr(c, func)

This will put all custom functions within the class c to global scope.

like image 1
Rocky Li Avatar answered Oct 17 '22 19:10

Rocky Li