What is the accessibility of a package's `Private` context variables? The 2019 Stack Overflow Developer Survey Results Are InHow symbol lookup actually worksWhat are recommended guidelines for developing packages?How to properly handle mutual imports of multiple packages?How can Private functions be made completely opaque?Does one need to be careful about loading multiple (many) contexts or packages in the same session?WebServices context problemHow to pass rules to packagesA question regarding shadowed symbolsIs there any harm or benefit to Removing unneeded private symbols in packages?Information (??) of function defined in Package return the function with long name of variablesHow to resolve a context shadow problem (revised)

What does ひと匙 mean in this manga and has it been used colloquially?

One word riddle: Vowel in the middle

Can a flute soloist sit?

What do hard-Brexiteers want with respect to the Irish border?

Can a rogue use sneak attack with weapons that have the thrown property even if they are not thrown?

Which Sci-Fi work first showed weapon of galactic-scale mass destruction?

Return to UK after being refused entry years previously

Is flight data recorder erased after every flight?

Why not take a picture of a closer black hole?

Falsification in Math vs Science

How to support a colleague who finds meetings extremely tiring?

Is there a symbol for a right arrow with a square in the middle?

Is "plugging out" electronic devices an American expression?

How come people say “Would of”?

Why isn't airport relocation done gradually?

What do the Banks children have against barley water?

Protecting Dualbooting Windows from dangerous code (like rm -rf)

Can you compress metal and what would be the consequences?

Why hard-Brexiteers don't insist on a hard border to prevent illegal immigration after Brexit?

Why do we hear so much about the Trump administration deciding to impose and then remove tariffs?

Button changing it's text & action. Good or terrible?

"as much details as you can remember"

Should I use my personal e-mail address, or my workplace one, when registering to external websites for work purposes?

Did Scotland spend $250,000 for the slogan "Welcome to Scotland"?



What is the accessibility of a package's `Private` context variables?



The 2019 Stack Overflow Developer Survey Results Are InHow symbol lookup actually worksWhat are recommended guidelines for developing packages?How to properly handle mutual imports of multiple packages?How can Private functions be made completely opaque?Does one need to be careful about loading multiple (many) contexts or packages in the same session?WebServices context problemHow to pass rules to packagesA question regarding shadowed symbolsIs there any harm or benefit to Removing unneeded private symbols in packages?Information (??) of function defined in Package return the function with long name of variablesHow to resolve a context shadow problem (revised)










5












$begingroup$


I've been reading up on how Mathematica handles contexts, $Context, $ContextPath, and a few of the tutorials they have on Packages.



What I'm wondering about is how the functions defined in, say, CustomPackage` are able to access the variables in CustomPackage`Private`.



For example,



BeginPackage["CustomPackage`"]

MyFunction::usage = "MyFunction[arg1] adds 5 to arg1."

Begin["`Private`"]

abc=5;
MyFunction[arg1_] := arg1 + abc;

End[]
EndPackage[]


When I load the package <<CustomPackage` the $ContextPath will have CustomPackage` on it, but not CustomPackage`Private`



So how does MyFunction know the value of abc at the delayed function call (when it is called) if the Private` context isn't on the $ContextPath










share|improve this question











$endgroup$
















    5












    $begingroup$


    I've been reading up on how Mathematica handles contexts, $Context, $ContextPath, and a few of the tutorials they have on Packages.



    What I'm wondering about is how the functions defined in, say, CustomPackage` are able to access the variables in CustomPackage`Private`.



    For example,



    BeginPackage["CustomPackage`"]

    MyFunction::usage = "MyFunction[arg1] adds 5 to arg1."

    Begin["`Private`"]

    abc=5;
    MyFunction[arg1_] := arg1 + abc;

    End[]
    EndPackage[]


    When I load the package <<CustomPackage` the $ContextPath will have CustomPackage` on it, but not CustomPackage`Private`



    So how does MyFunction know the value of abc at the delayed function call (when it is called) if the Private` context isn't on the $ContextPath










    share|improve this question











    $endgroup$














      5












      5








      5





      $begingroup$


      I've been reading up on how Mathematica handles contexts, $Context, $ContextPath, and a few of the tutorials they have on Packages.



      What I'm wondering about is how the functions defined in, say, CustomPackage` are able to access the variables in CustomPackage`Private`.



      For example,



      BeginPackage["CustomPackage`"]

      MyFunction::usage = "MyFunction[arg1] adds 5 to arg1."

      Begin["`Private`"]

      abc=5;
      MyFunction[arg1_] := arg1 + abc;

      End[]
      EndPackage[]


      When I load the package <<CustomPackage` the $ContextPath will have CustomPackage` on it, but not CustomPackage`Private`



      So how does MyFunction know the value of abc at the delayed function call (when it is called) if the Private` context isn't on the $ContextPath










      share|improve this question











      $endgroup$




      I've been reading up on how Mathematica handles contexts, $Context, $ContextPath, and a few of the tutorials they have on Packages.



      What I'm wondering about is how the functions defined in, say, CustomPackage` are able to access the variables in CustomPackage`Private`.



      For example,



      BeginPackage["CustomPackage`"]

      MyFunction::usage = "MyFunction[arg1] adds 5 to arg1."

      Begin["`Private`"]

      abc=5;
      MyFunction[arg1_] := arg1 + abc;

      End[]
      EndPackage[]


      When I load the package <<CustomPackage` the $ContextPath will have CustomPackage` on it, but not CustomPackage`Private`



      So how does MyFunction know the value of abc at the delayed function call (when it is called) if the Private` context isn't on the $ContextPath







      packages core-language scoping contexts






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 3 hours ago









      m_goldberg

      88.5k873200




      88.5k873200










      asked 6 hours ago









      w1resw1res

      20314




      20314




















          3 Answers
          3






          active

          oldest

          votes


















          5












          $begingroup$


          So how does MyFunction know the value of abc at the delayed function call (when it is called) if the Private` context isn't on the $ContextPath




          There is a misunderstanding here. You are assuming that abc is searched for in some context only when MyFunction[something] is evaluated. This is not the case.



          $Context and $ContextPath only affect how source code is parsed (not how expressions are evaluated). In other words, they only affect how the text you write in the package file is interpreted and converted into in-memory expressions. Once the package has been loaded with Get, this interpretation has already happened. MyFunction has been interpreted as the symbol CustomPackage`MyFunction and abc has been interpreted as CustomPackage`Private`abc, according to the value of $Context and $ContextPath at the time each was read. These are the full names of these symbols and this is how they exist in memory.



          Load the package and try this:



          Block[$ContextPath,
          Print@Definition[MyFunction]
          ]


          You'll see the following printed:



          CustomPackage`MyFunction[CustomPackage`Private`arg1_] := 
          CustomPackage`Private`arg1+CustomPackage`Private`abc


          As you can see, a context is always associated with every symbol.






          share|improve this answer











          $endgroup$




















            4












            $begingroup$

            All symbols are created at load time, so when you do:



            BeginPackage["X`"];

            x::usage="Declaring x as an exported symbol in the X` context";

            Begin["`SomePrivateContext`"];

            x[a_]:=b

            End[];

            EndPackage[];


            x was created as X`x but the DownValues of x reference X`SomePrivateContext`a and X`SomePrivateContext`b which were created at the time the function was defined. These symbols are unique, so that reference only ever points that a single object.






            share|improve this answer









            $endgroup$




















              4












              $begingroup$

              Begin["`Private`"]; sets the current $Context to "CustomPackage `Private`". This causes two things:



              • The symbol abc will be searched in the current context first, thus in"CustomPackage`Private`". Only if it is not found there, the search goes on along $ContextPath.


              • If no matching symbol is found this way, a new symbol abc is created, namely in the current $Context which is "CustomPackage`Private`". So the full symbol name is "CustomPackage`Private`abc".


              For example, running your code in a fresh kernel and executing



              ??MyFunction


              reveals that the full definition of MyFunction is




              MyFunction[CustomPackage`Private`arg1_]:=CustomPackage`Private`arg1+CustomPackage`Private`abc




              Moreover, with



               ?*`abc


              you see that the only symbol in all contexts that matches abc is CustomPackage`Private`abc and has the value 5 assigned to it.






              share|improve this answer











              $endgroup$













                Your Answer





                StackExchange.ifUsing("editor", function ()
                return StackExchange.using("mathjaxEditing", function ()
                StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
                StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["$", "$"], ["\\(","\\)"]]);
                );
                );
                , "mathjax-editing");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "387"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: false,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: null,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );













                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f194963%2fwhat-is-the-accessibility-of-a-packages-private-context-variables%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                5












                $begingroup$


                So how does MyFunction know the value of abc at the delayed function call (when it is called) if the Private` context isn't on the $ContextPath




                There is a misunderstanding here. You are assuming that abc is searched for in some context only when MyFunction[something] is evaluated. This is not the case.



                $Context and $ContextPath only affect how source code is parsed (not how expressions are evaluated). In other words, they only affect how the text you write in the package file is interpreted and converted into in-memory expressions. Once the package has been loaded with Get, this interpretation has already happened. MyFunction has been interpreted as the symbol CustomPackage`MyFunction and abc has been interpreted as CustomPackage`Private`abc, according to the value of $Context and $ContextPath at the time each was read. These are the full names of these symbols and this is how they exist in memory.



                Load the package and try this:



                Block[$ContextPath,
                Print@Definition[MyFunction]
                ]


                You'll see the following printed:



                CustomPackage`MyFunction[CustomPackage`Private`arg1_] := 
                CustomPackage`Private`arg1+CustomPackage`Private`abc


                As you can see, a context is always associated with every symbol.






                share|improve this answer











                $endgroup$

















                  5












                  $begingroup$


                  So how does MyFunction know the value of abc at the delayed function call (when it is called) if the Private` context isn't on the $ContextPath




                  There is a misunderstanding here. You are assuming that abc is searched for in some context only when MyFunction[something] is evaluated. This is not the case.



                  $Context and $ContextPath only affect how source code is parsed (not how expressions are evaluated). In other words, they only affect how the text you write in the package file is interpreted and converted into in-memory expressions. Once the package has been loaded with Get, this interpretation has already happened. MyFunction has been interpreted as the symbol CustomPackage`MyFunction and abc has been interpreted as CustomPackage`Private`abc, according to the value of $Context and $ContextPath at the time each was read. These are the full names of these symbols and this is how they exist in memory.



                  Load the package and try this:



                  Block[$ContextPath,
                  Print@Definition[MyFunction]
                  ]


                  You'll see the following printed:



                  CustomPackage`MyFunction[CustomPackage`Private`arg1_] := 
                  CustomPackage`Private`arg1+CustomPackage`Private`abc


                  As you can see, a context is always associated with every symbol.






                  share|improve this answer











                  $endgroup$















                    5












                    5








                    5





                    $begingroup$


                    So how does MyFunction know the value of abc at the delayed function call (when it is called) if the Private` context isn't on the $ContextPath




                    There is a misunderstanding here. You are assuming that abc is searched for in some context only when MyFunction[something] is evaluated. This is not the case.



                    $Context and $ContextPath only affect how source code is parsed (not how expressions are evaluated). In other words, they only affect how the text you write in the package file is interpreted and converted into in-memory expressions. Once the package has been loaded with Get, this interpretation has already happened. MyFunction has been interpreted as the symbol CustomPackage`MyFunction and abc has been interpreted as CustomPackage`Private`abc, according to the value of $Context and $ContextPath at the time each was read. These are the full names of these symbols and this is how they exist in memory.



                    Load the package and try this:



                    Block[$ContextPath,
                    Print@Definition[MyFunction]
                    ]


                    You'll see the following printed:



                    CustomPackage`MyFunction[CustomPackage`Private`arg1_] := 
                    CustomPackage`Private`arg1+CustomPackage`Private`abc


                    As you can see, a context is always associated with every symbol.






                    share|improve this answer











                    $endgroup$




                    So how does MyFunction know the value of abc at the delayed function call (when it is called) if the Private` context isn't on the $ContextPath




                    There is a misunderstanding here. You are assuming that abc is searched for in some context only when MyFunction[something] is evaluated. This is not the case.



                    $Context and $ContextPath only affect how source code is parsed (not how expressions are evaluated). In other words, they only affect how the text you write in the package file is interpreted and converted into in-memory expressions. Once the package has been loaded with Get, this interpretation has already happened. MyFunction has been interpreted as the symbol CustomPackage`MyFunction and abc has been interpreted as CustomPackage`Private`abc, according to the value of $Context and $ContextPath at the time each was read. These are the full names of these symbols and this is how they exist in memory.



                    Load the package and try this:



                    Block[$ContextPath,
                    Print@Definition[MyFunction]
                    ]


                    You'll see the following printed:



                    CustomPackage`MyFunction[CustomPackage`Private`arg1_] := 
                    CustomPackage`Private`arg1+CustomPackage`Private`abc


                    As you can see, a context is always associated with every symbol.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited 5 hours ago

























                    answered 6 hours ago









                    SzabolcsSzabolcs

                    164k14448946




                    164k14448946





















                        4












                        $begingroup$

                        All symbols are created at load time, so when you do:



                        BeginPackage["X`"];

                        x::usage="Declaring x as an exported symbol in the X` context";

                        Begin["`SomePrivateContext`"];

                        x[a_]:=b

                        End[];

                        EndPackage[];


                        x was created as X`x but the DownValues of x reference X`SomePrivateContext`a and X`SomePrivateContext`b which were created at the time the function was defined. These symbols are unique, so that reference only ever points that a single object.






                        share|improve this answer









                        $endgroup$

















                          4












                          $begingroup$

                          All symbols are created at load time, so when you do:



                          BeginPackage["X`"];

                          x::usage="Declaring x as an exported symbol in the X` context";

                          Begin["`SomePrivateContext`"];

                          x[a_]:=b

                          End[];

                          EndPackage[];


                          x was created as X`x but the DownValues of x reference X`SomePrivateContext`a and X`SomePrivateContext`b which were created at the time the function was defined. These symbols are unique, so that reference only ever points that a single object.






                          share|improve this answer









                          $endgroup$















                            4












                            4








                            4





                            $begingroup$

                            All symbols are created at load time, so when you do:



                            BeginPackage["X`"];

                            x::usage="Declaring x as an exported symbol in the X` context";

                            Begin["`SomePrivateContext`"];

                            x[a_]:=b

                            End[];

                            EndPackage[];


                            x was created as X`x but the DownValues of x reference X`SomePrivateContext`a and X`SomePrivateContext`b which were created at the time the function was defined. These symbols are unique, so that reference only ever points that a single object.






                            share|improve this answer









                            $endgroup$



                            All symbols are created at load time, so when you do:



                            BeginPackage["X`"];

                            x::usage="Declaring x as an exported symbol in the X` context";

                            Begin["`SomePrivateContext`"];

                            x[a_]:=b

                            End[];

                            EndPackage[];


                            x was created as X`x but the DownValues of x reference X`SomePrivateContext`a and X`SomePrivateContext`b which were created at the time the function was defined. These symbols are unique, so that reference only ever points that a single object.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered 6 hours ago









                            b3m2a1b3m2a1

                            28.6k359165




                            28.6k359165





















                                4












                                $begingroup$

                                Begin["`Private`"]; sets the current $Context to "CustomPackage `Private`". This causes two things:



                                • The symbol abc will be searched in the current context first, thus in"CustomPackage`Private`". Only if it is not found there, the search goes on along $ContextPath.


                                • If no matching symbol is found this way, a new symbol abc is created, namely in the current $Context which is "CustomPackage`Private`". So the full symbol name is "CustomPackage`Private`abc".


                                For example, running your code in a fresh kernel and executing



                                ??MyFunction


                                reveals that the full definition of MyFunction is




                                MyFunction[CustomPackage`Private`arg1_]:=CustomPackage`Private`arg1+CustomPackage`Private`abc




                                Moreover, with



                                 ?*`abc


                                you see that the only symbol in all contexts that matches abc is CustomPackage`Private`abc and has the value 5 assigned to it.






                                share|improve this answer











                                $endgroup$

















                                  4












                                  $begingroup$

                                  Begin["`Private`"]; sets the current $Context to "CustomPackage `Private`". This causes two things:



                                  • The symbol abc will be searched in the current context first, thus in"CustomPackage`Private`". Only if it is not found there, the search goes on along $ContextPath.


                                  • If no matching symbol is found this way, a new symbol abc is created, namely in the current $Context which is "CustomPackage`Private`". So the full symbol name is "CustomPackage`Private`abc".


                                  For example, running your code in a fresh kernel and executing



                                  ??MyFunction


                                  reveals that the full definition of MyFunction is




                                  MyFunction[CustomPackage`Private`arg1_]:=CustomPackage`Private`arg1+CustomPackage`Private`abc




                                  Moreover, with



                                   ?*`abc


                                  you see that the only symbol in all contexts that matches abc is CustomPackage`Private`abc and has the value 5 assigned to it.






                                  share|improve this answer











                                  $endgroup$















                                    4












                                    4








                                    4





                                    $begingroup$

                                    Begin["`Private`"]; sets the current $Context to "CustomPackage `Private`". This causes two things:



                                    • The symbol abc will be searched in the current context first, thus in"CustomPackage`Private`". Only if it is not found there, the search goes on along $ContextPath.


                                    • If no matching symbol is found this way, a new symbol abc is created, namely in the current $Context which is "CustomPackage`Private`". So the full symbol name is "CustomPackage`Private`abc".


                                    For example, running your code in a fresh kernel and executing



                                    ??MyFunction


                                    reveals that the full definition of MyFunction is




                                    MyFunction[CustomPackage`Private`arg1_]:=CustomPackage`Private`arg1+CustomPackage`Private`abc




                                    Moreover, with



                                     ?*`abc


                                    you see that the only symbol in all contexts that matches abc is CustomPackage`Private`abc and has the value 5 assigned to it.






                                    share|improve this answer











                                    $endgroup$



                                    Begin["`Private`"]; sets the current $Context to "CustomPackage `Private`". This causes two things:



                                    • The symbol abc will be searched in the current context first, thus in"CustomPackage`Private`". Only if it is not found there, the search goes on along $ContextPath.


                                    • If no matching symbol is found this way, a new symbol abc is created, namely in the current $Context which is "CustomPackage`Private`". So the full symbol name is "CustomPackage`Private`abc".


                                    For example, running your code in a fresh kernel and executing



                                    ??MyFunction


                                    reveals that the full definition of MyFunction is




                                    MyFunction[CustomPackage`Private`arg1_]:=CustomPackage`Private`arg1+CustomPackage`Private`abc




                                    Moreover, with



                                     ?*`abc


                                    you see that the only symbol in all contexts that matches abc is CustomPackage`Private`abc and has the value 5 assigned to it.







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited 6 hours ago

























                                    answered 6 hours ago









                                    Henrik SchumacherHenrik Schumacher

                                    59.7k582166




                                    59.7k582166



























                                        draft saved

                                        draft discarded
















































                                        Thanks for contributing an answer to Mathematica Stack Exchange!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid


                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.

                                        Use MathJax to format equations. MathJax reference.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f194963%2fwhat-is-the-accessibility-of-a-packages-private-context-variables%23new-answer', 'question_page');

                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        How to create a command for the “strange m” symbol in latex? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)How do you make your own symbol when Detexify fails?Writing bold small caps with mathpazo packageplus-minus symbol with parenthesis around the minus signGreek character in Beamer document titleHow to create dashed right arrow over symbol?Currency symbol: Turkish LiraDouble prec as a single symbol?Plus Sign Too Big; How to Call adfbullet?Is there a TeX macro for three-legged pi?How do I get my integral-like symbol to align like the integral?How to selectively substitute a letter with another symbol representing the same letterHow do I generate a less than symbol and vertical bar that are the same height?

                                        Българска екзархия Съдържание История | Български екзарси | Вижте също | Външни препратки | Литература | Бележки | НавигацияУстав за управлението на българската екзархия. Цариград, 1870Слово на Ловешкия митрополит Иларион при откриването на Българския народен събор в Цариград на 23. II. 1870 г.Българската правда и гръцката кривда. От С. М. (= Софийски Мелетий). Цариград, 1872Предстоятели на Българската екзархияПодмененият ВеликденИнформационна агенция „Фокус“Димитър Ризов. Българите в техните исторически, етнографически и политически граници (Атлас съдържащ 40 карти). Berlin, Königliche Hoflithographie, Hof-Buch- und -Steindruckerei Wilhelm Greve, 1917Report of the International Commission to Inquire into the Causes and Conduct of the Balkan Wars

                                        Чепеларе Съдържание География | История | Население | Спортни и природни забележителности | Културни и исторически обекти | Религии | Обществени институции | Известни личности | Редовни събития | Галерия | Източници | Литература | Външни препратки | Навигация41°43′23.99″ с. ш. 24°41′09.99″ и. д. / 41.723333° с. ш. 24.686111° и. д.*ЧепелареЧепеларски Linux fest 2002Начало на Зимен сезон 2005/06Национални хайдушки празници „Капитан Петко Войвода“Град ЧепелареЧепеларе – народният ски курортbgrod.orgwww.terranatura.hit.bgСправка за населението на гр. Исперих, общ. Исперих, обл. РазградМузей на родопския карстМузей на спорта и скитеЧепеларебългарскибългарскианглийскитукИстория на градаСки писти в ЧепелареВремето в ЧепелареРадио и телевизия в ЧепелареЧепеларе мами с родопски чар и добри пистиЕвтин туризъм и снежни атракции в ЧепелареМестоположениеИнформация и снимки от музея на родопския карст3D панорами от ЧепелареЧепелареррр