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()
Is this feature available in Python?
Solution 1:
In Julia two modules can export
the same function and Julia will automatically detect such an issue, i.e. even if you export
them they will not overwrite each other:
julia> module A
export x
x() = "a"
end
Main.A
julia> module B
export x
x() = "b"
end
Main.B
julia> using .A, .B
julia> x()
WARNING: both B and A export "x"; uses of it in module Main must be qualified
That is why in Julia the common practice is to do using
not import
.
In Python doing an equivalent is considered to be a bad practice in production code.
As a side comment: another relevant difference between Julia and Python is that in Julia module
concept is detached from the files/directory structure. You can have many modules in one file or you can have many files that form a single module.
Solution 2:
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 class
es 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.