4

With this simple module:

#!/usr/bin/python
#file: foo.py
import ctypes

class Foo(ctypes.Structure):
   pass

In iPython:

In [1]: import foo
In [2]: foo.
Foo
ctypes

ctypes is a module used inside the module foo, it should not be shown to the user. The goal is to hide ctypes from the auto-completion offered by ipython

Is this solution too cumbersome?

import ctypes as __ctypes
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
nowox
  • 25,978
  • 39
  • 143
  • 293
  • 1
    I would say it's too cumbersome, yes (use a single underscore, at most). *Why* do you want to hide some of the names in your module's namespace? Have you considered using `__all__` (see http://stackoverflow.com/q/44834/3001761), if this is a concern for wildcard imports? – jonrsharpe Nov 04 '15 at 17:44
  • The user might get confused if it does not know that `ctypes` is a module used by my module, but not a feature of it. I am expecting the user to use the auto-completion to see what objects he can use. One solution is to create a static class inside the module where all the usable methods are located. I don't think it is a better solution – nowox Nov 04 '15 at 17:49
  • Why do you think anyone would be confused by that? There's no need for a static class, you could expose a list (just like `__all__`, and maybe even using that name!) of the names of attributes that are supposed to be used, but this happens whenever you have any imports and rarely proves to be a sticking point. – jonrsharpe Nov 04 '15 at 17:49

1 Answers1

4

I usually use __all__ for that. Your code would become something like:

import ctypes

# Note here
___all__ = []

class Foo(ctypes.Structure):
    pass

# Note here
__all__ += ['Foo']

If you do from foo import *, you'll see only Foo (or whatever else you add to __all__).

Community
  • 1
  • 1
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
  • You don't need to add `'Foo'` at the end, I'd say it's neater to include all the names at the top of the file. – jonrsharpe Nov 04 '15 at 17:50
  • I agree it doesn't have to go after the class definition (after all, it's just a string), but I usually place it neither at the beginning nor at the end, but rather grouped with the class/function/whatever. This way, if I modify the definition, I remember to modify the all as well. – Ami Tavory Nov 04 '15 at 17:52
  • It does not work. If you `import` this module on iPython, the auto-completion will still show all the members of the module including `ctypes`. – nowox Nov 04 '15 at 17:54
  • @nowox See correction - it affects `from something import *`. – Ami Tavory Nov 04 '15 at 18:03