Search code examples
pythonimportpython-importlib

Import method in folder with reserved word


I have the following file structure:

root
|
folder1 -> lambda -> lambda.py -> myMethod()
|
test-> lambda_test -> test_lambda.py

I would like to import lambda.myMethod() into my test.lambda.py file for testing but python understandably complains about lambda being a keyword.

I tried various combos with importlib without much luck.


Solution

  • Here's your directory structure:

    folder1/lambda/__init__.py
                   lambda.py
    test/lambda_test/test_lambda.py
    

    And the contents of each file:

    # folder1/lambda/__init__.py
    import importlib
    lambda_module = importlib.import_module('lambda.lambda')
    
    # folder1/lambda/lambda.py
    def hello_world():
        print("hello world")
    
    # test/lambda_test/test_lambda.py
    import importlib
    import sys
    
    sys.path.append("../../folder1")
    my_lambda_import = importlib.import_module("lambda")
    
    my_lambda_import.lambda_module.hello_world()