I'm not sure I got how to define private functions right. When I'm writing a package mathematica, I just do this:

```
BeginPackage["myPackage`"]
myPublicFunction::usage="myPublicFunction blahblahblah";
Begin["Private"]
myPrivateFunction[input_]:= ... ;
myPublicFunction[input_]:= ... ;
End[]
EndPackage[]
```

Is this the correct way or am I missing something?

Thanks!

Yep, that's a correct way. It may pay off to understand some of the internal package mechanics. Mathematica contexts are similar to namespaces in other languages. They can be nested. Every symbol belongs to some context. At any given moment, some context is "current". Whenever a new symbol is created, the system must decide to which context the symbol will belong. This happens at parse-time. The fundamental quantity (variable) here is `$ContextPath`

. It is basically the search path for symbols. It is a list of contexts, and whenever the system sees a new symbol, it tests if the symbol with the same short name (that is, the name of the symbol proper, without the context) exists in some context on the `$ContextPath`

. If it does exist, then the given occurrence of the symbol will be associated with that existing one. If it does not, then the symbol is created in a current context. Note that this is a dynamic thing - if you change the `$ContextPath`

at any moment, the next symbol occurrence can be associated with a different symbol.

Anyways, what `BeginPackage`

does is that it simply replaces the current value of $ContextPath with just `{youPublicPackageContext, "System'"}`

, plus possibly additional contexts that you publicly import through the second optional argument of `BeginPackage`

. Therefore, all symbols that are in the "public" section, are parsed into the public context, if they are not in "System'" or other contexts that you import. And what `EndPackage`

does is to restore the value of the `$ContextPath`

to what it was before you started loading the package. So, technically the usage message is not the only way to make a symbol public in your main context - you could just as well simply type a symbol with a semicolon, like `myFunction;`

(this practice is discouraged, I just mentioned it to clarify the mechanism). Now, what happens when you enter `Begin["'Private'"]`

is that the current context becomes `YourContext'Private'`

(a sub-context). The `$ContextPath`

is not changed. Therefore, any symbol entered there, which does not exist in your public package or other imported packages (that is, contexts currently on the `$ContextPath`

), automatically is parsed into the `'Private'`

subcontext.

What really makes these symbols private is that whenever you import your package into some other context (package), only the main package is added to the `$ContextPath`

, but not its sub-packages. Technically, you can break encapsulation by manually adding `YourPackage'Private'`

to the $ContextPath (say, `PrependTo[$ContextPath, YourPackage'Private']`

), and then all your private functions and other symbols will become public in that particular context where you do the import. Again, this practice is discouraged, but it explains the mechanics. The bottom line is that the notion of private or public can be entirely understood when we know how symbols are parsed, and what are the manipulations with `$ContextPath`

and `$Context`

(another system variable giving the value of the current context), that are performed by commands such as `Begin`

and `BeginPackage`

. To put it another way, one could, in principle, emulate the actions of `BeginPackage`

,`Begin`

, `End`

and `EndPackage`

with a user-defined code. There are just a few principles operating here (which I tried to outline above), and the mechanism itself is in fact very much exposed to the user, so that if, in some rare cases, one may want some other behavior, one can make some "custom" manipulations with `$ContextPath`

and `Context`

, to ensure some non-standard way of symbol parsing and therefore, control package-scale encapsulation in some "non-standard" way. I am not encouraging this, just mentioning to emphasize that the mechanism is in fact much simpler and much more controllable than it may seem on the surface.

Similar Questions

I used to have a config file in PHP that define'd some constants. It doesn't seem to work anymore since upgrading to PHP 5.4. Here's an example: //config.php define('CONSTANT', 'foo'); //page.php requ

I'm a beginner in Mathematica programming. My code is not running as expected. I wonder if anyone could examine what goes wrong? Here is part of the code. F[{k_, n_, x_}] = Which[k == 0, f[a, b, x], k

I am preparing an R package for submission to CRAN. R CMD check gives me the following NOTE: Foreign function calls to a different package: .Fortran(cinc, ... PACKAGE = cmprsk) .Fortran(crstm,

I want to repeat a function n times on a table, For n=2 I have the following code, How can I be sure that the function had run twice since my fc is differend every time? smat = Table[{9, 8, 10}, {3}]

I define one function in my .emacs, I want to activate ECB and goto to directory when I enter f12, but it does not work (defun my-toggle-ecb () (ecb-activate) (ecb-goto-window-directories) ) (global-s

Is there a Mathematica function that provides results equivalent to the unique() function in MATLAB? I realize I could use the Union[] function to obtain the unique elements of a list, but I would lik

Following on from a similar question, I would like to be able to allow users to extend a class in my package which uses private (not export-ed) functions. A minimal working example: # my_package/R/Mai

I'm trying to find a shortcut to the following loop. When developing a mathematica's package one is implementing changes to the .m file's code and then want to test the changes in another notebook. Th

I'm developing an R package, and I'd like to set some function aliases, e.g. if I have defined a function named foo, I'd like it to be available under bar symbol too. Note that I'm aware of @alias tag

Imagine I've defined a recursive factorial in Mathematica, like this: Clear[fact] fact[0] = 1 fact[n_] := n fact[n - 1] Evaluating fact[10] confirms that the function works and terminates. A bit of a

I'm really confused by the behavior of this function: david[x_] := 5; 6; 7 david[] returns 7 but david[3] returns 5 Why does this happen? I'd think the second case should also return 7; why doesn'

I have define several .cpp files. One of them needs the package RcppArmadillo; The others need the package Rcpp. After my Rcpp package is generated and when i install it, I compile several errors as f

For some list of 2-d points, e.g. data = {{1, 2}, {3,4}, {3, 6}}, and some analytic function, e.g. f[x] = x^2, I want to select out only those points that lie beneath the curve, i.e., test for each p

I can define private member fields in module pattern using the code below var myClass = function(){ var private_field1,private_field_2; var private_func1 = function(){ //....... } //......... var myO

I came across this class java.io.FileSystem and noticed it has many methods that I currently need in my project. However the class is package-private, and so I am accessing the needed methods using re

So Mathematica is different from other dialects of lisp because it blurs the lines between functions and macros. In Mathematica if a user wanted to write a mathematical function they would likely use

I just created a VERY large neural net, albeit on very powerful hardware, and imagine my shock and disappointment, when I realized that NeuralFit[] from NeuralNetworks` package only seems to use one c

I want to define inline function within alert class currently i have following implementation. Alert.show('my mesage', 'header message', Alert.OK, Alert.No, doAction) private function doAction(event:C

when you define a package in oracle there is a like a header and then a body. One must define all parameters in both locations. I want to make one of the parameters optional for the calling program (I

It is possible to define a prototype of a function or in some way indicate to Ruby that a function exists even though it may not be defined yet? I have lots of classes like this: class Program FIRST

I have a function f(t)=2/(2-t). It is not so hard to get the rth derivative at t=0 (i.e. 2^(-r)*r!) without using Mathematica. In the case of Mathematica calculation, I can get the r-th derivative whe

Hello all together, I'm wondering if you are able to define or instantiate a function for example in the constructor of a class. Let's say you have this simple class: class cTest { public: cTest( bool

define a function that has a single parameter of type string which which displayed on console. invoke the function passing it a message. ensure the function ignores any returned value open System let

I am working on a function that I would like to define more than one prototype and was wondering if this is possible. I know visual studios does this for some of their function calls but wasn't sure i

I have a matlab m-file in order to draw an integral as below. I want to rewrite this code in mathematica but I don't know any equivalent function for subs()!! Does any body help me? syms x y w; fun =

I have the following procedure: Private Sub btnRptEmployeePayToMarket_MouseDown(ByValsender As Object, ByVal myButton As System.Windows.Forms.MouseEventArgs) Handles btnRptEmployeePayToMarket.MouseDo

In my Codeigniter controller have the following private function which validates file uploads. private function avatar_file_validation() { $config['upload_path'] = './uploads/avatars/'; $config['allo

I have the following javascript: (JSFiddle) $(function () { function Cat() { this.Meow = function (sound) { alert(Meow: + sound); } this.Kick = function () { MakeNoise(); } var MakeNoise = function

To illustrate my problem here is a toy example: F[x_] := Module[{out}, If[x > 1, out = 1/2, out = 1 ]; out ]; The function can be evaluated and plotted. However when I try to numerically integrate

I'd like to know how can I call Mathematica functions from Python. I appreciate a example, for example, using the Mathematica function Prime. I had search about MathLink but how to use it in Python is

Is there a way to define a function on a specific domain in mathematica? I need this because I want to invert a function which is only monotonic on a specific domain. For example: f[x_]:=x^2 g[x_]:=I

I'm monkey-patching some of the jQuery's Draggable code*. The goal is to avoid modifying the original source files and patch dynamically one of the internal functions. The function _generatePosition i

If I try private[com.company.foo] def bar(xml: XmlPath) = { I get [error] ... ']' expected but '.' found. [error] private[com. [error] ^ What's with that? I can only make it package-private to com.*

I have here a complicated bit of code that is not pretty nor easy to follow, but it represents a simplification of a larger body of code I am working with. I am a Mathematica novice and have already r

I want to do something like this (define a lambda function based on some condition): auto update; if(condition) { update = [this]() {this->someField += 1;}; } else { update = [this]() {this->som

How can I make a Mathematica graphics that copies the behaviour of complex_plot in sage? i.e. ... takes a complex function of one variable, and plots output of the function over the specified xrange

How do you define a special operator in Mathematica, for example a special type of additive or multiplicative operator? I did that in the past but I can't recall where I put the code. I tried defining

How can I suppress the following error with the @SuppressWarning annotation? The method Foo.trololo() does not override the inherited method from Bar since it is private to a different package So fa

I'm using Mathematica 7. I have an interpolated function, here's an example: pressures = WeatherData[Chicago, Pressure, {2010, 8}] // DeleteCases[#, {_, _Missing}] & // Map[{AbsoluteTime[#[[1]

Just curious how Mathematica users debug their code when encounter run-time errors. I feel Mathematica is so powerful that most programming tasks can be replaced with it but when it has bugs the incon

I'm having some issues simplifying some functions in mathematica. In a program I wrote I have a few functions calculated with the Sum function, many of the terms end up being multiplied by zero. I wan

Although the Abstract Algebra Add-on is a beautiful package for Mathematica, imo there is nothing that beats GAP, at least not for Group Theory. When I looked at Sage a few years ago, I found that sai

I am developing an application package in mathematica with workbench and it is starting to get complex with multpiple versions and components. I read in some mathematica documentation (http://referenc

Is there any way to not allow private construction in friend function, In case we do have private constructor with friend function in our class. Only Static method should be responsible for object cre

So the have seem something like this today: $$('input').each(function() { // do something }); What is the difference between that and this: $$('input').each( // do something ); The private function

I have attended a job interview. The interviewer asked me why you need private variable. If you achieve something by defining a variable private, can't you achieve the same by defining any other acces

why protected becomes private to other classes in different package of subclass .but it is still protected in same package of super class. package a; class A { protected a; } package b; class B extend

I have created a package 'mypackage' (with a namespace 'mypackage' attached) In this package there is a function that I can call either with 'myfunction' or 'mypackage::myfunction' Now I want to rep

I have concrete_impl.h (as is): #ifdef TUPLE_ITERATOR_WITH_INDEX #define TUPLE_ITERATOR TUPLE_ITERATOR_NO_INDEX #define iterate_tuple_fname iterate_tuple_id #else #define TUPLE_ITERATOR TUPLE_ITERATOR

How do I declare a private function in Fortran?