6

My question arises from this question, in which a user got himself confused by unknowingly rebinding the built-in global set. Is there a straightforward way to get python to warn you when you attempt to override a built-in?

I'm thinking more specifically of Mathematica. In Mathematica all built-ins have attribute Protected. If you try to redefine Set, it will tell you that Set is Protected and leave it unchanged, possibly saving you from massive confusion later on when things that ought to work stop doing so for no obvious reason. If you really seriously want to redefine Set you can still do it -- you just have to Unprotect it first. And you can Protect your own symbols, too, to protect them from accidental redefinition.

Perhaps experienced pythoners don't need this, but it would be nice if there were something like this for newbies like me. (Come to think of it, I've been programming Mathematica for 15 years and Protected still occasionally saves my bacon.)

Community
  • 1
  • 1
Leon Avery
  • 856
  • 2
  • 8
  • 20
  • 1
    Nope, Python won't warn you about setting names that shadow built-ins. That's your own responsibility. Sometimes naming a variable `id` is just the ticket, I wouldn't want to be warned about the built-in `id()` function every time I do that. – Martijn Pieters Nov 28 '14 at 14:59
  • 3
    `pylint` will detect this, but only keywords (e.g. `def`, `for`) are "protected" from reassignment. – jonrsharpe Nov 28 '14 at 14:59
  • 1
    Use a linter if you are concerned about this kind of thing; a good linter will warn you about this and much more. – Martijn Pieters Nov 28 '14 at 15:01
  • @HuStmpHrrr: that won't actually protect your environment if someone already rebound those names. You'd be better of using the [`__builtin__` module](https://docs.python.org/2/library/__builtin__.html) to reference built-ins. That won't help the OP however; they are afraid they'll accidentally shadow built-ins *themselves*. – Martijn Pieters Nov 28 '14 at 15:14
  • @MartijnPieters ok, i didn't understand the problem good. – Jason Hu Nov 28 '14 at 15:19

1 Answers1

5

Use http://www.pylint.org/

def set():
    pass

Will generate this warning:

[W0622, set] Redefining built-in 'set'

You can run it over your files after you write them, or use it in e.g. Vim as you go. Most IDE's will also generate this sort of information

Paul Collingwood
  • 9,053
  • 3
  • 23
  • 36
  • Thanks -- that's helpful. The only limitation I see is that it won't be much help in an interactive session. I wonder how hard it would be to add some kind of automated linting to `ipython`? – Leon Avery Nov 28 '14 at 15:13