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)

Why not take a picture of a closer black hole?

What is the most effective way of iterating a std::vector and why?

If I score a critical hit on an 18 or higher, what are my chances of getting a critical hit if I roll 3d20?

Output the Arecibo Message

Is a "Democratic" Oligarchy-Style System Possible?

Did Section 31 appear in Star Trek: The Next Generation?

For what reasons would an animal species NOT cross a *horizontal* land bridge?

Why is the maximum length of OpenWrt’s root password 8 characters?

What tool would a Roman-age civilization have for the breaking of silver and other metals into dust?

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

Origin of "cooter" meaning "vagina"

Apparent duplicates between Haynes service instructions and MOT

Reference request: Oldest number theory books with (unsolved) exercises?

Have you ever entered Singapore using a different passport or name?

What could be the right powersource for 15 seconds lifespan disposable giant chainsaw?

What is the motivation for a law requiring 2 parties to consent for recording a conversation

Delete all lines which don't have n characters before delimiter

How to type this arrow in math mode?

Why was M87 targetted for the Event Horizon Telescope instead of Sagittarius A*?

FPGA - DIY Programming

Is bread bad for ducks?

How to answer pointed "are you quitting" questioning when I don't want them to suspect

What is the closest word meaning "respect for time / mindful"

Multiply Two Integer Polynomials



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)










6












$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$
















    6












    $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$














      6












      6








      6





      $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 8 hours ago









      m_goldberg

      88.5k873200




      88.5k873200










      asked 11 hours ago









      w1resw1res

      20814




      20814




















          4 Answers
          4






          active

          oldest

          votes


















          7












          $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$

            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$




















              5












              $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$




















                1












                $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?




                because "CustomPackage`Private`" is the value of $Context when MyFunction is defined (i.e. it is not just $ContextPath that determines what a function sees but also what is on $Context).




                TL:DR



                This is a timely question because it indirectly touches upon the competing imperatives of developers and end-users. To the question itself:



                The whole point of packages is that they are a form of encapsulation that allows developers to, without interferance, implement functionality for end-users without bothering them with the underlying details. In particular, the encapsulation involves controlling namespaces so that the underlying details can involve symbols that help implement the functionality but ultimately don't end-up polluting a user's namespace. All symbols defined in a "*`Private`" namespace are created for exactly this purpose.



                Hence in the OP's example, the variable abc is an underlying detail for the implementation of the public MyFunction. The developer needs the "detail" of abc but this particular symbol but is of no direct interest to an end-user who typically just ends up calling MyFunction[].



                The package layout achieves this encapsulation by manipulating $ContextPath and $Context as the control-flow passes through the package when it is first loaded. This is described in the other answers and documentation but it can be useful to see it directly:



                loc[n_] := Sow[<|
                "Location" -> n,
                "$Context" -> $Context,
                "$ContextPath" -> $ContextPath|>];

                Reap[

                loc@1;

                BeginPackage["CustomPackage`"];

                loc@2;

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

                Begin["`Private`"];

                loc@3;

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

                End[];

                loc@4;

                EndPackage[];

                loc@5
                ]// Last // Dataset


                enter image description here




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




                Yes, this implements both the public exporting of all CustomPackage functions but without polluting end-users namespaces with implementation details. In code around Location 3, all packages are cleared out thereby eliminating possible conflicts with existing abc definitions in currently loaded packages. This is encapsulation benefitting developers but the encapsulation benefitting end-users, as observed, is that on exiting (at Location 5) $ContextPath contains "CustomPackage`" (to provide access to MyFunction) but not "CustomPackage`Private`" thereby shielding users from symbols used in MyFunction's implementation.



                A programmatic confirmation at Location 5 gives:



                MemberQ["CustomPackage`"]@$ContextPath, 
                MemberQ["CustomPackage`Private`"]@$ContextPath,
                Context["abc"]

                True, False, "Global`"



                At Location 3 in the control-flow, the symbol abc is not contained in any of the contexts defined in $ContextPath, ("CustomPackage`", or "System`") nor is it (yet) in the context defined in $Context ("CustomPackage`Private`"). Consequently, the name abc gets created in the context currently set to $Context. At this location $Context has value "CustomPackage`Private`" and hence the symbol CustomPackage`Private`abc is created. When the control flow then moves on to MyFunction[], "CustomPackage`Private`" is still the value of $Context so this function "sees" abc (hence it not just $ContextPath that determines what a function sees but what is on both$ContextPath and $Context).



                Note how the convention of placing usage definitions at Location 2 is ostensibly for documentation purposes but its more important role is to ensure that the function goes into the package's context (see $Context at Location 2) before subsequently being made available in the implementation and for end-users (see $ContextPath at Locations 3 and 5).



                IMO it is kind of cool how these placement protocols just work intuitively without necessarily keeping front-of-mind all the control-flow manipulations, variable-creation mechanisms etc taking place behind the scenes. Hence this means being very careful changing the framework but also IMHO the time is ripe for such extensions given that the line between users/developers may well be in the process of blurring.






                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

























                  4 Answers
                  4






                  active

                  oldest

                  votes








                  4 Answers
                  4






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  7












                  $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$

















                    7












                    $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$















                      7












                      7








                      7





                      $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 10 hours ago

























                      answered 10 hours ago









                      SzabolcsSzabolcs

                      164k14448946




                      164k14448946





















                          5












                          $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$

















                            5












                            $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$















                              5












                              5








                              5





                              $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 11 hours ago









                              b3m2a1b3m2a1

                              28.6k359165




                              28.6k359165





















                                  5












                                  $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$

















                                    5












                                    $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$















                                      5












                                      5








                                      5





                                      $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 10 hours ago

























                                      answered 11 hours ago









                                      Henrik SchumacherHenrik Schumacher

                                      59.7k582166




                                      59.7k582166





















                                          1












                                          $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?




                                          because "CustomPackage`Private`" is the value of $Context when MyFunction is defined (i.e. it is not just $ContextPath that determines what a function sees but also what is on $Context).




                                          TL:DR



                                          This is a timely question because it indirectly touches upon the competing imperatives of developers and end-users. To the question itself:



                                          The whole point of packages is that they are a form of encapsulation that allows developers to, without interferance, implement functionality for end-users without bothering them with the underlying details. In particular, the encapsulation involves controlling namespaces so that the underlying details can involve symbols that help implement the functionality but ultimately don't end-up polluting a user's namespace. All symbols defined in a "*`Private`" namespace are created for exactly this purpose.



                                          Hence in the OP's example, the variable abc is an underlying detail for the implementation of the public MyFunction. The developer needs the "detail" of abc but this particular symbol but is of no direct interest to an end-user who typically just ends up calling MyFunction[].



                                          The package layout achieves this encapsulation by manipulating $ContextPath and $Context as the control-flow passes through the package when it is first loaded. This is described in the other answers and documentation but it can be useful to see it directly:



                                          loc[n_] := Sow[<|
                                          "Location" -> n,
                                          "$Context" -> $Context,
                                          "$ContextPath" -> $ContextPath|>];

                                          Reap[

                                          loc@1;

                                          BeginPackage["CustomPackage`"];

                                          loc@2;

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

                                          Begin["`Private`"];

                                          loc@3;

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

                                          End[];

                                          loc@4;

                                          EndPackage[];

                                          loc@5
                                          ]// Last // Dataset


                                          enter image description here




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




                                          Yes, this implements both the public exporting of all CustomPackage functions but without polluting end-users namespaces with implementation details. In code around Location 3, all packages are cleared out thereby eliminating possible conflicts with existing abc definitions in currently loaded packages. This is encapsulation benefitting developers but the encapsulation benefitting end-users, as observed, is that on exiting (at Location 5) $ContextPath contains "CustomPackage`" (to provide access to MyFunction) but not "CustomPackage`Private`" thereby shielding users from symbols used in MyFunction's implementation.



                                          A programmatic confirmation at Location 5 gives:



                                          MemberQ["CustomPackage`"]@$ContextPath, 
                                          MemberQ["CustomPackage`Private`"]@$ContextPath,
                                          Context["abc"]

                                          True, False, "Global`"



                                          At Location 3 in the control-flow, the symbol abc is not contained in any of the contexts defined in $ContextPath, ("CustomPackage`", or "System`") nor is it (yet) in the context defined in $Context ("CustomPackage`Private`"). Consequently, the name abc gets created in the context currently set to $Context. At this location $Context has value "CustomPackage`Private`" and hence the symbol CustomPackage`Private`abc is created. When the control flow then moves on to MyFunction[], "CustomPackage`Private`" is still the value of $Context so this function "sees" abc (hence it not just $ContextPath that determines what a function sees but what is on both$ContextPath and $Context).



                                          Note how the convention of placing usage definitions at Location 2 is ostensibly for documentation purposes but its more important role is to ensure that the function goes into the package's context (see $Context at Location 2) before subsequently being made available in the implementation and for end-users (see $ContextPath at Locations 3 and 5).



                                          IMO it is kind of cool how these placement protocols just work intuitively without necessarily keeping front-of-mind all the control-flow manipulations, variable-creation mechanisms etc taking place behind the scenes. Hence this means being very careful changing the framework but also IMHO the time is ripe for such extensions given that the line between users/developers may well be in the process of blurring.






                                          share|improve this answer











                                          $endgroup$

















                                            1












                                            $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?




                                            because "CustomPackage`Private`" is the value of $Context when MyFunction is defined (i.e. it is not just $ContextPath that determines what a function sees but also what is on $Context).




                                            TL:DR



                                            This is a timely question because it indirectly touches upon the competing imperatives of developers and end-users. To the question itself:



                                            The whole point of packages is that they are a form of encapsulation that allows developers to, without interferance, implement functionality for end-users without bothering them with the underlying details. In particular, the encapsulation involves controlling namespaces so that the underlying details can involve symbols that help implement the functionality but ultimately don't end-up polluting a user's namespace. All symbols defined in a "*`Private`" namespace are created for exactly this purpose.



                                            Hence in the OP's example, the variable abc is an underlying detail for the implementation of the public MyFunction. The developer needs the "detail" of abc but this particular symbol but is of no direct interest to an end-user who typically just ends up calling MyFunction[].



                                            The package layout achieves this encapsulation by manipulating $ContextPath and $Context as the control-flow passes through the package when it is first loaded. This is described in the other answers and documentation but it can be useful to see it directly:



                                            loc[n_] := Sow[<|
                                            "Location" -> n,
                                            "$Context" -> $Context,
                                            "$ContextPath" -> $ContextPath|>];

                                            Reap[

                                            loc@1;

                                            BeginPackage["CustomPackage`"];

                                            loc@2;

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

                                            Begin["`Private`"];

                                            loc@3;

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

                                            End[];

                                            loc@4;

                                            EndPackage[];

                                            loc@5
                                            ]// Last // Dataset


                                            enter image description here




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




                                            Yes, this implements both the public exporting of all CustomPackage functions but without polluting end-users namespaces with implementation details. In code around Location 3, all packages are cleared out thereby eliminating possible conflicts with existing abc definitions in currently loaded packages. This is encapsulation benefitting developers but the encapsulation benefitting end-users, as observed, is that on exiting (at Location 5) $ContextPath contains "CustomPackage`" (to provide access to MyFunction) but not "CustomPackage`Private`" thereby shielding users from symbols used in MyFunction's implementation.



                                            A programmatic confirmation at Location 5 gives:



                                            MemberQ["CustomPackage`"]@$ContextPath, 
                                            MemberQ["CustomPackage`Private`"]@$ContextPath,
                                            Context["abc"]

                                            True, False, "Global`"



                                            At Location 3 in the control-flow, the symbol abc is not contained in any of the contexts defined in $ContextPath, ("CustomPackage`", or "System`") nor is it (yet) in the context defined in $Context ("CustomPackage`Private`"). Consequently, the name abc gets created in the context currently set to $Context. At this location $Context has value "CustomPackage`Private`" and hence the symbol CustomPackage`Private`abc is created. When the control flow then moves on to MyFunction[], "CustomPackage`Private`" is still the value of $Context so this function "sees" abc (hence it not just $ContextPath that determines what a function sees but what is on both$ContextPath and $Context).



                                            Note how the convention of placing usage definitions at Location 2 is ostensibly for documentation purposes but its more important role is to ensure that the function goes into the package's context (see $Context at Location 2) before subsequently being made available in the implementation and for end-users (see $ContextPath at Locations 3 and 5).



                                            IMO it is kind of cool how these placement protocols just work intuitively without necessarily keeping front-of-mind all the control-flow manipulations, variable-creation mechanisms etc taking place behind the scenes. Hence this means being very careful changing the framework but also IMHO the time is ripe for such extensions given that the line between users/developers may well be in the process of blurring.






                                            share|improve this answer











                                            $endgroup$















                                              1












                                              1








                                              1





                                              $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?




                                              because "CustomPackage`Private`" is the value of $Context when MyFunction is defined (i.e. it is not just $ContextPath that determines what a function sees but also what is on $Context).




                                              TL:DR



                                              This is a timely question because it indirectly touches upon the competing imperatives of developers and end-users. To the question itself:



                                              The whole point of packages is that they are a form of encapsulation that allows developers to, without interferance, implement functionality for end-users without bothering them with the underlying details. In particular, the encapsulation involves controlling namespaces so that the underlying details can involve symbols that help implement the functionality but ultimately don't end-up polluting a user's namespace. All symbols defined in a "*`Private`" namespace are created for exactly this purpose.



                                              Hence in the OP's example, the variable abc is an underlying detail for the implementation of the public MyFunction. The developer needs the "detail" of abc but this particular symbol but is of no direct interest to an end-user who typically just ends up calling MyFunction[].



                                              The package layout achieves this encapsulation by manipulating $ContextPath and $Context as the control-flow passes through the package when it is first loaded. This is described in the other answers and documentation but it can be useful to see it directly:



                                              loc[n_] := Sow[<|
                                              "Location" -> n,
                                              "$Context" -> $Context,
                                              "$ContextPath" -> $ContextPath|>];

                                              Reap[

                                              loc@1;

                                              BeginPackage["CustomPackage`"];

                                              loc@2;

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

                                              Begin["`Private`"];

                                              loc@3;

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

                                              End[];

                                              loc@4;

                                              EndPackage[];

                                              loc@5
                                              ]// Last // Dataset


                                              enter image description here




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




                                              Yes, this implements both the public exporting of all CustomPackage functions but without polluting end-users namespaces with implementation details. In code around Location 3, all packages are cleared out thereby eliminating possible conflicts with existing abc definitions in currently loaded packages. This is encapsulation benefitting developers but the encapsulation benefitting end-users, as observed, is that on exiting (at Location 5) $ContextPath contains "CustomPackage`" (to provide access to MyFunction) but not "CustomPackage`Private`" thereby shielding users from symbols used in MyFunction's implementation.



                                              A programmatic confirmation at Location 5 gives:



                                              MemberQ["CustomPackage`"]@$ContextPath, 
                                              MemberQ["CustomPackage`Private`"]@$ContextPath,
                                              Context["abc"]

                                              True, False, "Global`"



                                              At Location 3 in the control-flow, the symbol abc is not contained in any of the contexts defined in $ContextPath, ("CustomPackage`", or "System`") nor is it (yet) in the context defined in $Context ("CustomPackage`Private`"). Consequently, the name abc gets created in the context currently set to $Context. At this location $Context has value "CustomPackage`Private`" and hence the symbol CustomPackage`Private`abc is created. When the control flow then moves on to MyFunction[], "CustomPackage`Private`" is still the value of $Context so this function "sees" abc (hence it not just $ContextPath that determines what a function sees but what is on both$ContextPath and $Context).



                                              Note how the convention of placing usage definitions at Location 2 is ostensibly for documentation purposes but its more important role is to ensure that the function goes into the package's context (see $Context at Location 2) before subsequently being made available in the implementation and for end-users (see $ContextPath at Locations 3 and 5).



                                              IMO it is kind of cool how these placement protocols just work intuitively without necessarily keeping front-of-mind all the control-flow manipulations, variable-creation mechanisms etc taking place behind the scenes. Hence this means being very careful changing the framework but also IMHO the time is ripe for such extensions given that the line between users/developers may well be in the process of blurring.






                                              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?




                                              because "CustomPackage`Private`" is the value of $Context when MyFunction is defined (i.e. it is not just $ContextPath that determines what a function sees but also what is on $Context).




                                              TL:DR



                                              This is a timely question because it indirectly touches upon the competing imperatives of developers and end-users. To the question itself:



                                              The whole point of packages is that they are a form of encapsulation that allows developers to, without interferance, implement functionality for end-users without bothering them with the underlying details. In particular, the encapsulation involves controlling namespaces so that the underlying details can involve symbols that help implement the functionality but ultimately don't end-up polluting a user's namespace. All symbols defined in a "*`Private`" namespace are created for exactly this purpose.



                                              Hence in the OP's example, the variable abc is an underlying detail for the implementation of the public MyFunction. The developer needs the "detail" of abc but this particular symbol but is of no direct interest to an end-user who typically just ends up calling MyFunction[].



                                              The package layout achieves this encapsulation by manipulating $ContextPath and $Context as the control-flow passes through the package when it is first loaded. This is described in the other answers and documentation but it can be useful to see it directly:



                                              loc[n_] := Sow[<|
                                              "Location" -> n,
                                              "$Context" -> $Context,
                                              "$ContextPath" -> $ContextPath|>];

                                              Reap[

                                              loc@1;

                                              BeginPackage["CustomPackage`"];

                                              loc@2;

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

                                              Begin["`Private`"];

                                              loc@3;

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

                                              End[];

                                              loc@4;

                                              EndPackage[];

                                              loc@5
                                              ]// Last // Dataset


                                              enter image description here




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




                                              Yes, this implements both the public exporting of all CustomPackage functions but without polluting end-users namespaces with implementation details. In code around Location 3, all packages are cleared out thereby eliminating possible conflicts with existing abc definitions in currently loaded packages. This is encapsulation benefitting developers but the encapsulation benefitting end-users, as observed, is that on exiting (at Location 5) $ContextPath contains "CustomPackage`" (to provide access to MyFunction) but not "CustomPackage`Private`" thereby shielding users from symbols used in MyFunction's implementation.



                                              A programmatic confirmation at Location 5 gives:



                                              MemberQ["CustomPackage`"]@$ContextPath, 
                                              MemberQ["CustomPackage`Private`"]@$ContextPath,
                                              Context["abc"]

                                              True, False, "Global`"



                                              At Location 3 in the control-flow, the symbol abc is not contained in any of the contexts defined in $ContextPath, ("CustomPackage`", or "System`") nor is it (yet) in the context defined in $Context ("CustomPackage`Private`"). Consequently, the name abc gets created in the context currently set to $Context. At this location $Context has value "CustomPackage`Private`" and hence the symbol CustomPackage`Private`abc is created. When the control flow then moves on to MyFunction[], "CustomPackage`Private`" is still the value of $Context so this function "sees" abc (hence it not just $ContextPath that determines what a function sees but what is on both$ContextPath and $Context).



                                              Note how the convention of placing usage definitions at Location 2 is ostensibly for documentation purposes but its more important role is to ensure that the function goes into the package's context (see $Context at Location 2) before subsequently being made available in the implementation and for end-users (see $ContextPath at Locations 3 and 5).



                                              IMO it is kind of cool how these placement protocols just work intuitively without necessarily keeping front-of-mind all the control-flow manipulations, variable-creation mechanisms etc taking place behind the scenes. Hence this means being very careful changing the framework but also IMHO the time is ripe for such extensions given that the line between users/developers may well be in the process of blurring.







                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited 2 hours ago

























                                              answered 2 hours ago









                                              Ronald MonsonRonald Monson

                                              3,1531633




                                              3,1531633



























                                                  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

                                                  Reverse int within the 32-bit signed integer range: [−2^31, 2^31 − 1]Combining two 32-bit integers into one 64-bit integerDetermine if an int is within rangeLossy packing 32 bit integer to 16 bitComputing the square root of a 64-bit integerKeeping integer addition within boundsSafe multiplication of two 64-bit signed integersLeetcode 10: Regular Expression MatchingSigned integer-to-ascii x86_64 assembler macroReverse the digits of an Integer“Add two numbers given in reverse order from a linked list”

                                                  Category:Fedor von Bock Media in category "Fedor von Bock"Navigation menuUpload mediaISNI: 0000 0000 5511 3417VIAF ID: 24712551GND ID: 119294796Library of Congress authority ID: n96068363BnF ID: 12534305fSUDOC authorities ID: 034604189Open Library ID: OL338253ANKCR AUT ID: jn19990000869National Library of Israel ID: 000514068National Thesaurus for Author Names ID: 341574317ReasonatorScholiaStatistics

                                                  Kiel Indholdsfortegnelse Historie | Transport og færgeforbindelser | Sejlsport og anden sport | Kultur | Kendte personer fra Kiel | Noter | Litteratur | Eksterne henvisninger | Navigationsmenuwww.kiel.de54°19′31″N 10°8′26″Ø / 54.32528°N 10.14056°Ø / 54.32528; 10.14056Oberbürgermeister Dr. Ulf Kämpferwww.statistik-nord.deDen danske Stats StatistikKiels hjemmesiderrrWorldCat312794080n790547494030481-4