0

This question has been asked before in 2011 (Checking if a symbol is defined), however, since then Mathematica has had several major versions.

As such I am wondering if there is a simpler solution to the problem of checking if a certain symbol has already been defined (to avoid overwriting it)? ValueQ apparently has some flaws and the other answers provide rather complicated solutions to such a simple problem.

Qubit
  • 1,175
  • 9
  • 18

1 Answers1

0

In what situations are you concerned about 'overwriting it'. If it is a symbol that you have defined you can Protect it.

Remove[x];
x = 1;
Protect[x];

x = 2
(* Set::wrsym: Symbol x is Protected. *)

If you are concerned about shadowing, use Contexts.

Update

symbols = Names["Global`*"];
NotebookEvaluate[FileNameJoin[{NotebookDirectory[], "test.nb"}], InsertResults -> False];
Complement[Names["Global`*"], symbols]
(* {"xyzzy"} *)
Rohit Namjoshi
  • 669
  • 5
  • 17
  • Assume I know nothing about the notebook and what symbols it has defined (I also can't assume any symbols are protected as I do not know the contents of the notebook). I now wish to define some number of symbols myself, but do not want to overwrite ones that have already been defined. I agree that one possible solution would be the use of a context. This however does not answer the original question. – Qubit Aug 14 '19 at 08:34
  • @Qubit Added example to address your use case. – Rohit Namjoshi Aug 15 '19 at 18:51