5

Suppose we have the following package ABC.wl.

BeginPackage["ABC`"]

Begin["DEF`"]

f1 = 0;
f2[x_] := x + 1

End[]

EndPackage[]

Using the package from a notebook yields the following definitions.

Needs["ABC`"]
In[1]:= Definition[DEF`f1]
Out[1]= DEF`f1 = 0
In[2]:= Definition[DEF`f2]
Out[2]= DEF`f2[DEF`x_] := DEF`x + 1

How can DEF`* be "moved" to Global` such that the definitions are of the same form as if they were defined in Global`?

In[1]:= Definition[f1]
Out[1]= f1 = 0
In[2]:= Definition[f2]
Out[2]= f2[x_] := x + 1

Update Some motivation as requested by Szabolcs: this is useful e.g. when you want to print definitions from a context in a package without touching the source code of the package.

Markus
  • 53
  • 5

2 Answers2

3

If you really want this, you can do e.g. the following:

Block[{$ContextPath = {"System`", "DEF`"}}, 
  Scan[
    (Context[#] = "Global`") &, 
    Names["DEF`*"]
  ]
] 

Here, Block was used just to make sure that Names will return short symbol string names, rather than fully-qualified ones.

This will move all symbols from DEF` to Global`, which automatically make DEF` context empty, and it will be then automatically removed from a list of available contexts, as per Contexts[].

Leonid Shifrin
  • 114,335
  • 15
  • 329
  • 420
3

On my system, Mathematica 10.1 under Windows, I got an error using Leonid's code:

Context::cxdup: Cannot set Context[DEF`x] to Global`, since a symbol already exists with name x and context Global`. >>

I seem to need something like this to avoid it:

Block[{$ContextPath = {"System`", "DEF`"}}, 
 Scan[(Quiet[Remove @@ {"Global`" <> StringTrim[#, __ ~~ "`"]}]; 
    Context[#] = "Global`") &, Names["DEF`*"]]]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
  • 1
    Apparently, I have not considered the case when one or more of the symbols already exist in Global`, in which case one gets this error. Do you mind if I incorporate in some form your observation in my (updated) answer? – Leonid Shifrin May 11 '20 at 15:43
  • @Leonid No, of course I don't mind. I thought in case this was a version difference I should post separately. – Mr.Wizard May 11 '20 at 20:59