4

Suppose I have:

+MyPackage/+MySubPackage2/some_function.m

How can I generate the string 'MyPackage.MySubPackage2.some_function' from within this some_function.m when it's executing?

  • mfilename(), dbstack(), what(), etc. all just give 'some_function'
  • meta.package.fromName requires the string we're after as its input
  • parsing the full path (mfilename('fullpath')) or meta.package.getAllPackages() etc. seems to be the only way...

Seems that calling mfilename('class') in a class inside a package gives the right answer, but there's no equivalent for plain functions...

...or is there? Feels like I'm missing something obvious...

Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
  • 2
    Don't you know the name of the file you're editing when you write a function? :p – Cris Luengo Oct 30 '18 at 04:55
  • 1
    @CrisLuengo ...there are times when indeed I haven't the foggiest – Rody Oldenhuis Oct 30 '18 at 04:56
  • How about `dbstack ('-completenames')`? – jrook Oct 30 '18 at 05:48
  • @jrook nope, `S=dbstack ('-completenames'); S.name` just gives `some_function` – Rody Oldenhuis Oct 30 '18 at 05:59
  • The full path is stored in `S.file`. – jrook Oct 30 '18 at 06:00
  • 1
    @jrook Indeed. I can also get the full path using `mfilename('fullpath')`, but that's not what I'm after - I'm looking for the exact string you'd need to type into the MATLAB command line to call that function. – Rody Oldenhuis Oct 30 '18 at 06:01
  • 1
    The interesting part would be why you need this info. Perhaps the underlying problem could be solved without this? – Andy Oct 30 '18 at 09:14
  • 1
    @Andy I "need" if for the same reasons you "need" `mfilename` or `argv[0]` or `__name__` etc.: Resilience against renaming. Consistent help text generation. Reusable code that works correctly without any change in different packages. etc. Indeed, perhaps, for my immediate problem, I can do away with the need, but at this point it's just curiosity! Why is there such rich introspection everywhere, but not when packages are thrown in the mix... – Rody Oldenhuis Oct 30 '18 at 19:02

1 Answers1

3

If it is possible to import the containing package (say p1/p2), then:

function outputArg1 = some_function()
import p1.p2.*
t = @some_function;
func2str(t)
%ans  = 'p1.p2.some_function'
outputArg1 = ...;
end

The method in this answer may also be used (with some changes possibly) to automate the import process.

jrook
  • 3,459
  • 1
  • 16
  • 33
  • I guess this is the best I'm gonna get, considering the answer you linked to (thanks for that link!) The problem with your solution is: move this function to `+p14/+p45` and the code breaks. So indeed it seems, there is just no way to generate that string without parsing the full-path string...sounds like The MathWorks have a hole to fill – Rody Oldenhuis Oct 30 '18 at 19:01