I would like to control which methods appear when a user uses tab-completion on a custom object in ipython – in particular, I want to hide functions that I have deprecated. I still want these methods to be callable, but I don’t want users to see them and start using them if they are inspecting the object. Is this something that is possible?
Share
Partial answer for you. I’ll post the example code and then explain why its only a partial answer.
Code:
So now the caveat: they’re not methods (note the lack of self as the first variable). If you need your users (or your code) to be able to call im_class, im_func, or im_self on any of your deprecated methods, then this hack won’t work. Also, i’m pretty sure there’s going to be a performance hit because you’re defining each dep’d function inside
__getattr__. This won’t affect your other attribute lookups (had I put them in__getattribute__, that would be a different matter), but it will slow down access to those deprecated methods. This can be (largely, but not entirely) negated by putting each function definition inside its own if block, instead of doing a list-membership check, but, depending on how big your function is, that could be really annoying to maintain.UPDATE:
1) If you want to make the deprecated functions methods (and you do), just use
instead of
in the above snippet, and add self as the first argument to the function defs. It turns them into instancemethods (so you can use im_class, im_func, and im_self to your heart’s content).
2) If the
__getattr__hook didn’t thrill you, there’s another option (that I know of) (albiet, with its own caveats, and we’ll get to those): Put the deprecated functions definitions inside__init__, and hide them with a custom__dir__. Here’s what the above code would look like done this way:The advantage here is that you’re not defining the functions anew every lookup, which nets you speed. The disadvantage here is that because you’re not defining functions anew each lookup, they have to ‘persist’ (if you will). So, while the custom
__dir__method hides your deprecateds fromdir(hiddenObj)and, therefore, IPython’s tab-completion, they still exist in the instance’s__dict__attribute, where users can discover them.