# Move definition from one context to Global

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[DEFf1]
Out[1]= DEFf1 = 0
In[2]:= Definition[DEFf2]
Out[2]= DEFf2[DEFx_] := DEFx + 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.

• Mathematica will warn you if e.g. f1 is present in both the ABC​ and Global​ contexts. Do you really want to have the same symbol for different contexts? – J. M.'s ennui May 11 '20 at 14:35
• The context ABC  could be removed after the definitions have been moved to Global  to avoid the conflict. – Markus May 11 '20 at 14:41
• If you really want this, you can do e.g. the following: Block[{$ContextPath = {"System", "DEF"}}, Scan[(Context[#] = "Global") &, Names["DEF*"]]]. This will automatically make DEF  context empty, and it will be then automatically removed from a lit of available contexts, as per Contexts[]. – Leonid Shifrin May 11 '20 at 14:52 • Thank you Leonid. If you like you can write it as an answer. – Markus May 11 '20 at 15:03 • Can you add some context and explain the motivation? – Szabolcs May 11 '20 at 15:31 ## 2 Answers 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[].

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

Context::cxdup: Cannot set Context[DEFx] 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*"]]]

• 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