Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I import a namespace globally without explicitly calling import in each and every function?

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?

like image 991
Andrey Rubshtein Avatar asked Jan 16 '12 17:01

Andrey Rubshtein


People also ask

How do you import a namespace in Python?

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.

How do I import a 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.

How do you import all objects from a module into the current namespace in Python?

So __all__ specifies all modules that shall be loaded and imported into the current namespace when we use from <package> import * .

Do I need to import in every Python file?

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 .


1 Answers

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.

like image 50
Oli Avatar answered Sep 20 '22 20:09

Oli