Function definition inside Module with local symbol

Usually if I want to define a function using an expression I do:

expr=x^2;
f[x_]=expr;


which usually works and give f a defination.

But now if I want to do the same inside a Module:

Clear[f]
f = Module[{g, x,expr},
expr = x^2;
g[x_] = expr
];


then Information[f] would show that f has not a defination but instead an assignment. Why the first method does not work inside a Module?

• I suggest that you define functions the way the documentation recommends. Commented Apr 22, 2023 at 0:59
• @Ghoster What should I do if I have an expression in terms of a symbol and I want to make it into a function of that symbol? Commented Apr 23, 2023 at 16:46

Module[

You'll notice that this actually evaluates to something (it'll be something like x$41742^2). Furthermore, the symbol g inside the module is localized to that module (i.e. it's real name is something like g$12345). So, inside the module you've defined DownValues for g$12345, and in doing so, you made the whole Module evaluate to x$41742^2. This you then set to the Global f.
I know you didn't ask, but defining functions this way is fraught. The "this way" I'm referring to is by first creating an expression and then referring to that expression when creating DownValues. If you're going to do it this way, you might want to use Formal symbols (e.g. \[FormalA]). Or there are other ways to protect your definition from collisions.