How to avoid importing the same package name repeatedly in all functions in this package?
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
covariant_cat
am 5 Jun. 2018
Kommentiert: Walter Roberson
am 28 Apr. 2022
I have a package that contains n functions
+mypackwithlongname
+mypackwithlongname/f1.m
+mypackwithlongname/f2.m
...
+mypackwithlongname/fn.m
I found (with surprise) that these functions, although inside the same package, cannot call each other.
How can these functions call each other without doing "import mypackwithlongname.*" in every file? I don't want to explicitly write the package name in so many files because I will change package name in future versions. For the same reason I don't want to call functions with the package name like mypackwithlongname.f1. I'd like to make the code of f1 to fn completely independent of the package name. There's no reason they should.
Of course I can write a single function or script that returns the package's name. But I don't want to put this file anywhere outside the package because it's important in my application for the package to be self-contained instead of relying on anything external.
Why can't functions in the same package see each other without doing an import? Am I missing anything?
Related questions:
0 Kommentare
Akzeptierte Antwort
Ameya Deoras
am 9 Mär. 2019
I have avoided using packages primarily for this reason. One workaround that may work in some instances is to use a private folder and place the functions there. This limits who can call those functions to the parent folder only, but the functions themselves don't need any import or packagename. statements - they can call each other with abanadon. Now, if you want to expose those functions outside the package, you can create a wrapper as shown below.
Example:
C:\Temp\+TestPrivate\parentFun.m
C:\Temp\+TestPrivate\foo.m
C:\Temp\+TestPrivate\private\foo.m
C:\Temp\+TestPrivate\private\bar.m
Only functions within the package TestPrivate can call the private functions foo or bar, and foo and bar can call each other. Notice there's a package function called foo and also a private function called foo. The package function is simply a wrapper to the underlying private function (generic enough to be auto-generated). So, TestPrivate.foo() calls the private function foo(). It's content is as follows. As you can see, it should be fairly easy to auto-generate.
function varargout = foo(varargin)
% <Help copied from private foo>
[varargout{1:nargout}] = foo(varargin{:}); % This calls private\foo.m
Now how this affects performance is a difference question.
2 Kommentare
Gabriele Bellomia
am 27 Apr. 2022
Woah, this really is the only neat solution I found around, it works like a charm for me, thank you!
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Whos finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!