basically, what I want to do is add a function name to an outside reference in a safe sys.modules reference without copying the name...
best idea I got is to call a 3rd party function:

def myfunc(args):
    x = None
    return x
addname() # add 'myfunc' to sys.modules['/safe_ref/']

anyone got any ideas??
including other methods

perhaps defining the function using a referenced string name:

def (addname('myfunc'))(args):

the whole sys.modules['/safe_ref/'] thing is used by external programs

basically, I'm trying to query my interface's functions as it's imported

Recommended Answers

All 6 Replies

or I could just go with exec, but I was trying to avoid the loss in syntax highlights

def register(name, arguments, code):
    sys.modules['/safe_ref/'][name]=None; exec 'def %s(%s):%s'%(name, arguments, code) in globals()

register( 'myfunc', 'args', '''
    x = None
    return x
''')

I may just have to settle for this...

basically, what I want to do is add a function name to an outside reference in a safe sys.modules reference without copying the name...

Have you considered writing a decorator? Perhaps something like so:

@register
def myfunc(args):
    x = None
    return x

You could even set it up to allow multiple registries:

@register(myFunctionRegistry)
def myfunc(args):
    x = None
    return x

I'm not quite sure how you would implement it, but that seems like the most reasonable approach to take, given the semantics you want.

commented: Of course +14

decorators only work on function call, not on definition

decorators only work on function call, not on definition

On the contrary, the decorator is called once, immediately after the function's definition

>>> def deco(f):
...  print f.__name__, 'is being defined'
...  return f
... 
>>> @deco
... def foo(x):
...  return x * x
... 
foo is being defined
>>> foo(3)
9
>>> 

decorators only work on function call, not on definition

Actually, they can be either one, sort of; the decorator syntax is just syntactic sugar for calling the decorator function with the defined function as its first argument. That decorator function can be any higher-order function that takes a function as its first positional parameter, and returns a function as its only return value.

Defining a decorator operation that is invoked at function call requires wrapping the defined function in a closure, and returning the closure as the value of the decorator, but the decorator itself runs at define time.

well heck, you learn something new every day I guess :P
thanks guys, both of you get a +1 :)

@Schol: I understood grib's better than your explaination, though I still understood ;)
(I learn better by visual example, where if it hadn't been for grib, I'd probably still be questioning yours)
thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.