In order to avoid namespace bloating, I use packages. For example, let Foo
be a function in a package called FooPackage
function Foo()
disp('Foo');
end
I want to use this function in another function called Bar
.
function Bar()
InFunc1();
InFunc2();
InFunc3();
end
this function calls sub-functions. The Naive way is to say explicitly the package name in each call
function InFunc1()
FooPackage.Foo();
end
function InFunc2()
FooPackage.Foo();
end
function InFunc3()
FooPackage.Foo();
end
Alternatively I can use an import in each and every function:
function InFunc1()
import FooPackage.*
Foo();
end
function InFunc2()
import FooPackage.*
Foo();
end
function InFunc3()
import FooPackage.*
Foo();
end
Both of the ways are exhausting. The answer in here says that thes are the only ways. Does anyone has a better suggestion?
Importing is a way of pulling a name from somewhere else into the desired namespace. To refer to a variable, function, or class in Python one of the following must be true: The name is in the Python built-in namespace. The name is the current module's global namespace.
To add an imported namespaceIn Solution Explorer, double-click the My Project node for the project. In the Project Designer, click the References tab. In the Imported Namespaces list, select the check box for the namespace that you wish to add. In order to be imported, the namespace must be in a referenced component.
So __all__ specifies all modules that shall be loaded and imported into the current namespace when we use from <package> import * .
Python does not actually import a module that it has already imported (unless you force it to do so with the reload function), so you can safely put a import some_module statement into every module of your program that needs access to the names defined in some_module .
Maybe you could use a private
directory. The functions in the private
directory can be seen only by functions in its parent directory, and they can be called just by their names.
It's not a completely satisfying solution, but that can help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With