Strange namespace issue

Lele Gaifax lele at metapensiero.it
Mon Aug 10 14:42:38 EDT 2020


Hi all,

today I faced an issue that, although very easy to fix, left me wondering
about what causes it.

The context is an application that execute small scripts coming from an
external source (say, a database). The application first compile the script,
then execute it passing it some values: in the script I wrote this morning I
used a list comprehension, executing a method of an instance passed in in the
local context.

The following example illustrates the problem:

    class Test:
        def create_value(self, a):
            return a*2

    script = """\
    # This works
    cv = test.create_value
    x = []
    for i in range(3):
        x.append(cv(i))
    print(x)

    # This does not: NameError: name 'test' is not defined
    x = [test.create_value(i) for i in range(3)]
    print(x)

    # This neither: NameError: name 'cv' is not defined
    x = [cv(i) for i in range(3)]
    print(x)
    """

    code = compile(script, 'script', 'exec')
    exec(code, {}, {'test': Test()})

I must be missing something, as I cannot understand why within the list
comprehension the neither the name "test" nor the name "cv" are defined...

Thanks in advance for any enlightenment!

ciao, lele.
-- 
nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.
lele at metapensiero.it  |                 -- Fortunato Depero, 1929.



More information about the Python-list mailing list