Why can you import a package *after* using its content in a function?

霸气de小男生 提交于 2019-12-04 05:12:55

MATLAB performs static code analysis prior to evaluating a function in order to determine the variables/functions used by that function. Evaluation of the import statements is part of this static code analysis. This is by design because if you import a package and then use it's functions, MATLAB needs to know this during the static code analysis. As a result, regardless of where you put the import statement within your function, it will have the same effect as if it were at the beginning of the function.

You can easily test this by looking at the output of import which will list all of the current imported packages.

+test/a.m

function a(x)
    disp(import)
    import test.*
end

test.a()

%   test.*

This is why the documentation states to not put an import statement within a conditional.

Do not use import in conditional statements inside a function. MATLAB preprocesses the import statement before evaluating the variables in the conditional statements.

function a(x)
    disp(import)
    if x
        import test.*
    else
        import othertest.*
    end
end

test.a()

%   test.*
%   othertest.*

The only way to avoid this behavior is to allow the static code analyzer to determine (without a doubt) that an import statement won't be executed. We can do this by having our conditional statement be simply a logical value.

function a()
    disp(import)
    if true
        import test.*
    else
        import othertest.*
    end
end

test.a()

%   test.*

As far as importing compared to other languages, it really depends on the language. In Python for example, you must place the import before accessing the module contents. In my experience, this is the typical case but I'm sure there are many exceptions. Every language is going to be different.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!