Skip to content

Python functions in a script do not inherit enclosing scope #3

@ctrueden

Description

@ctrueden

As noted by @ian-coccimiglio here, scripts with functions do not inherit imported modules, nor other globals.

This script fails:

import numpy

def version():
    return numpy.__version__

print(version())

Whereas this script works:

import numpy

def version():
    global numpy
    return numpy.__version__

print(version())

Interestingly, SciJava #@ variables injected into the bindings are put into locals() but not globals(), which means they are inaccessible to functions even when the global keyword is used:

#@ ImageJ ij
print(ij)
print(f"-- Globals? {'ij' in globals()}")
print(f"-- Locals? {'ij' in locals()}")
print(f"-- Dir? {'ij' in dir()}")

yields:

plugin:net.imagej.ImageJ
-- Globals? False
-- Locals? True
-- Dir? True

So there are maybe two different bugs going on here?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions