pythonimportmodule

Export module components in Python


In Julia, it is possible to export a function (or a variable, struct, etc.) of a module, after which it can be called in another script without the namespace (once it has been imported). For example:

# helpers.jl
module helpers

function ordinary_function()
# bla bla bla
end

function exported_function()
# bla bla bla
end

export exported_function()
end
# main.jl
include("helpers.jl")
using .helpers

# we have to call the non-exported function with namespace
helpers.ordinary_function()

# but we can call the exported function without namespace
exported_function()

In Python, is there something I can do within the module, so that when the module is imported, the "exported" components can be called directly?


Solution

  • In Python importing is easier than this:

    # module.py
    def foo(): pass
    
    # file.py
    from module import foo
    foo()
    
    # file2.py
    from file import foo
    foo()
    

    This works with classes too.


    In Python you can also do something like this:

    import module
    # You have to call like this:
    module.foo()
    

    When you import a module, all the functions the module imported are considered part of the module. Using the example below:

    # file.py
    import module
    
    # file2.py
    import file
    file.module.foo()
    # or...
    from file import module
    module.foo()
    # ...or...
    from file.module import foo
    foo()
    

    Notice that in Python the export is not needed.

    Look at the documentation: no export keyword exists in Python.