# Tag Info

30

Link to the code on GitHub I have been using this. It's mostly Leonid's code from the stackoverflow question you linked to, but it uses Definition instead of DownValues. Symbol names are printed without any context, but the full symbol name is put into a Tooltip so you can always find out what context a symbol is in. Update FullDefinition[symbol] claims ...

25

Symbols are created in the current context during parsing. This should not be a problem in normal circumstances as the symbols are merely "initialized" without values or properties. See these posts for more information: Is it possible to use Begin and End inside a Manipulate? Why doesn't this use of Begin[] work? When does Mathematica create a new ...

22

The answer of @R.M. already explains the essence of the problem. You can streamline the process of removing the Combinatorica from the $ContextPath by loading it via Block[{$ContextPath}, Needs["Combinatorica"]] (or use Get intead of Needs, although Needs is a preferred way to load a package). In this way, you don't have to do anything afterwards, ...

19

The red colouring indicates shadowing — i.e., when a symbol originally in a particular context, is exposed to the current context path, thereby clashing with another symbol of the same name in a different context, also on the context path. Example of shadowing: Here is a short example that demonstrates this. Try it out in a fresh kernel (call Quit[] ...

17

Short answer: yes, it is possible. The problem is that parsing is done line-by-line only for the top-level code. For code inside some head(s), it is first parsed as a whole. Therefore, your f is parsed to Globalf, and this is why that symbol is used. Here is what you can do, schematically: DynamicModule[{x = 5}, With[{def = MakeBoxes[f[y_] := y^2 + 1;], ...

16

Shadowing occurs only when there are two functions with the same name that are in $ContextPath. So right after you do <<Combinatorica, do the following:$ContextPath = Rest@$ContextPath; What this does is that it removes Combinatorica (which is the package you just loaded). Now the only Graph function that's on the path is SystemGraph and you can ... 12 I am not sure these are the best ways but they should work. You could do what you did with Dimensions for all the symbols in Combinatorica For example, running this replaceAndLoad[context_String -> toContext_String] := Block[{$ContextPath}, Needs[context]; Scan[ToExpression[ toContext <> StringReplace[#, context ~~ sym__ :> sym] ...

11

One possibility would be to modify the notebook's stylesheet so that Input cells (or a clone) have something like: CellProlog -> ($ContextPath = DeleteDuplicates[Prepend[$ContextPath,"abc"]]) Then your package's context should be available to all the code:

11

Your specific problem looks like you somehow managed to not load the package properly (did you evaluate Get[...]?). There's also an excess space in your long-form call to f (just before EndPackage[]) that will give you an error. Although your package will work if you fix the typo, this is not in general a good way to define your function. To see why, try: ...

11

I would just use strings, for all their fragility: ClearAll[print]; print[sym_, {conts_String}] := With[{altptrn = Alternatives @@ Reverse[SortBy[{conts}, StringLength]]}, Print@StringReplace[ToString[InputForm@FullDefinition@sym], (x : (_ | "") ~~ altptrn ~~ y : (_ | "")) /; ! (x === "\"" && y === "\"") :> ...

10

I can now offer a solution which leverages the full power of the code formatter, in its new, more robust form. Load the formatter: Import["https://raw.github.com/lshifr/CodeFormatter/master/CodeFormatter.m"] Some examples: CodeFormatterSpelunk[RunThrough] CodeFormatterSpelunk[PacletManagerCreatePaclet] In the last example, using MakeBoxes ...

10

This question is not too distantly related to my own on StackOverflow: Exposing Symbols to $ContextPath Leonid provides an interesting approach there that could be adapted to your problem. Rojo provides a solution that creates "proxy symbols" but these are not 100% equivalent. Information no longer works correctly for example: ?? ComKSubsets This ... 9 I think, using contexts here is a sensible suggestion, particularly because you want to use several variables. One possible alternative is to set up a struct-like data structure, where encapsulation mechanism is based on Module-generated persistent variables. There were many discussions related to emulation of structs in Mathematica, but, given the ... 9 I don't have an access to Mathematica at the moment, so what follows is untested. What you observed can be understood by looking at the mechanics of package loading and symbols creation. I dealt with this problem before, and will re-post here verbatim my answer from the MathGroup thread: The setup and the problem Suppose you have two packages, the main ... 9 Well, here is a suggestion: you can overload Needs using Villegas-Gayley trick. To do this safely, here is a generator for local environments, where Needs will be overloaded: createTraceEnvironment[context_String]:= Module[{inNeeds}, Function[ code, InternalInheritedBlock[ ... 9 This is possible in the interactive session with$PreRead. I will adopt my solution to the same problem posted in this Mathgroup thread. To quote my explanation from there, the essence of the present solution is to delay the parsing of the code (body) that must be executed inside a given context until run-time, that is, replace code ...

8

The issue here is that you haven't actually defined myContextx, just plain old x. It is possible to access global variables within a context (that's exactly what happens when you use built-in function within a package), and that is what you have done. Clear[fun]; fun[] := Module[{}, Begin["myContext"]; x = 1; End[];]; fun[] This is undefined. ...

7

I have not tested this yet but here is one possible approach: contextFreeDefinition[sym_Symbol, contexts_List] := InternalInheritedBlock[{sym}, ClearAttributes[sym, ReadProtected]; If[contexts =!= {}, Message[contextFreeDefinition::contexts, contexts]]; Block[{ipf = ToString @ InputForm @ FullDefinition @ sym}, ipf = ...

7

The iterator variable in the package lives in the context that your package sets (in this case, mypackagePrivate), but the call to ParallelTable from inside your package does not distribute the definitions in your package, because the parallel functions only distribute contexts that are listed in $DistributedContexts. This is by default set to$Context, ...

6

It seems like the StandardForm (default for output) of Times in any context (or Plus, etc) is with the * and + symbols. But your assumption isn't wrong I think, the symbols * and + are mapped to System Times and System Plus. Try PrependTo[$ContextPath, "blo"]; bloTimes[a_, b_] := 8; FullForm@MakeExpression[RowBox[{"a", "*", "b"}], StandardForm] I ... 6 This works, though it'd be nicer to have a built-in way to do it: SetAttributes[fullyQualifiedName, {HoldAll, Listable}]; fullyQualifiedName[a_] := Context[a] <> SymbolName[Unevaluated@a] Some demonstrations: In[4]:= fullyQualifiedName[a] Out[4]= "Globala" In[5]:= foo = 3 Out[5]= 3 In[6]:= fullyQualifiedName[foo] Out[6]= "Globalfoo" In[7]:= ... 6 Here is an alternative: ClearAll[f]; SetAttributes[f, HoldAll]; f[a_Symbol] := Block[{$ContextPath = {"Test"}, $Context = "Test"}, ToString[Unevaluated@a] ]; It is based on the way Mathematica treats short and long names depending on the current settings of$Context and $ContextPath. The context "Test" must not exist for it to be ... 6 As Leonid has explained the problem is that the symbols are created and get their context at parse time, so if you need to avoid generating them in the current (usually "Global") context, using$PreRead as he explained is the only possibility. If you don't care that the symbols you use are created in the current context AND the context you want to evaluate ...

5

Here's one approach, although I don't think it will actually meet your needs. The main thing is that care needs to be taken to make sure symbols are created in the correct context, with context being set during parsing, not evaluation. moduleState[context_String] := With[{init = ToExpression[context <> "init"], state = ToExpression[context ...

5

Now, with v9, I can undelete this answer :) You could set a context dependent on a certain counter value. Add to your stylesheet, to the "Input" style, the following option CellContext:>"Section"<>ToString@CurrentValue[{"CounterValue", "Section"}]<>"" and in my few tests you get a context dependent on the last section number. It can ...

5

When this is unavoidable, I just refer to full contexts. This happens all the time when using Combinatorica, which defines Graph objects that conflict with V8's new built in Graph object. Here's a sample session (presented as an image to show highlighting and such):

5

See CellContext: The below dialog box can be found in Format -> Option Inspector or Edit -> Preferences -> Advanced -> Open Option Inspector. When using custom CellContext you will need to use Global to access global symbols, for example: data = RandomReal[NormalDistribution[], 100]; ListPlot[MovingAverage[data, GlobalwindowLength]] If you are ...

5

The explanation can be found in the doc to BeginPackage and Begin BeginPackage["context"] makes context and Systemthe only active contexts. Begin["context`"] resets the current context. Therefore, at the moment you first mention the symbol test it is not created it in the Global context. This can be seen from you (simplified) example ...

Only top voted, non community-wiki answers of a minimum length are eligible