Skip to content

Commit c96b89f

Browse files
committed
Improve module loading
1 parent 6382e5b commit c96b89f

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

src/functions_framework/__init__.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -140,10 +140,24 @@ def create_app(target=None, source=None, signature_type=None):
140140
# Set the environment variable if it wasn't already
141141
os.environ["FUNCTION_SIGNATURE_TYPE"] = signature_type
142142

143-
# Load the source file
144-
spec = importlib.util.spec_from_file_location("__main__", source)
143+
# Load the source file:
144+
# 1. Extract the module name from the source path
145+
realpath = os.path.realpath(source)
146+
directory, filename = os.path.split(realpath)
147+
name, extension = os.path.splitext(filename)
148+
149+
# 2. Create a new module
150+
spec = importlib.util.spec_from_file_location(name, realpath)
145151
source_module = importlib.util.module_from_spec(spec)
146-
sys.path.append(os.path.dirname(os.path.realpath(source)))
152+
153+
# 3. Add the directory of the source to sys.path to allow the function to
154+
# load modules relative to its location
155+
sys.path.append(directory)
156+
157+
# 4. Add the module to sys.modules
158+
sys.modules[name] = source_module
159+
160+
# 5. Execute the module
147161
spec.loader.exec_module(source_module)
148162

149163
app = flask.Flask(target, template_folder=template_folder)

tests/test_functions/module_is_correct/main.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
import os.path
1516
import typing
1617

1718

@@ -21,7 +22,9 @@ class TestClass:
2122

2223
def function(request):
2324
# Ensure that the module for any object in this file is set correctly
24-
assert TestClass.__mro__[0].__module__ == "__main__"
25+
_, filename = os.path.split(__file__)
26+
name, _ = os.path.splitext(filename)
27+
assert TestClass.__mro__[0].__module__ == name
2528

2629
# Ensure that calling `get_type_hints` on an object in this file succeeds
2730
assert typing.get_type_hints(TestClass) == {}

0 commit comments

Comments
 (0)