[Python-ideas] Jump to function as an an alternative to call function
Steven D'Aprano
steve at pearwood.info
Thu Aug 16 14:34:22 EDT 2018
On Thu, Aug 16, 2018 at 10:31:28AM +0200, Brice Parent wrote:
> If I understand well the need (I'm unsure I've had it myself), it would
> be easier to be able to import the function in the active context, like
> this:
>
> def foo(a):
> return a + c
>
> def bar(a, c):
> return foo(a)
>
> def bazz(a, c):
> import __file__.foo
> return foo(a)
[...]
> I'm not saying the syntax is the one that should be used (__file__
> possibly not existing may be a problem), not even saying that we should
> have this. I'm just showing a way to do the same thing with an easier
> (to me) syntax.
The problem isn't that __file__ doesn't exist, it is that import DOES
exist and does something completely unsuitable:
def bazz(a, c):
# Make the *name* foo a local
foo = globals()['__file__'].foo # (roughly)
return foo(a)
But this doesn't change the scoping rules used when calling foo. It
still runs using lexical scope, which means the a+c line in foo()
still refers to the global variable c.
What we would need is a completely different command, not "import",
perhaps "load":
def bazz(a, c):
foo = load('foo')
return foo(a)
which would be equivalent to this pseudocode:
def bazz(a, c):
get the source code of foo (hopefully still available!)
foo = compile(source code as inner function)
call foo
or possibly:
def bazz(a, c):
make a copy of foo and its bytecode
change all(?) the LOAD_GLOBAL bytecode to LOAD_DEREF
call the modified copy of foo
Both implementations seem clunky, fragile and likely to be slow to me.
--
Steve
More information about the Python-ideas
mailing list