1

I'm relatively new to Python.

When I did C/C++ programming, I used the internal classes quite often. For example, in some_file.cc, we may implement a class in the anonymous namespace to prevent it from being used outside. This is useful as a helper class specific to that file.

Then, how we can do a similar thing in Python?

chanwcom
  • 4,420
  • 8
  • 37
  • 49
  • Python is almost always editable by text editor, so security measures like this aren't near as useful – Natecat Mar 29 '16 at 21:44
  • 1
    Possible duplicate of [Data Hiding in Python Class](http://stackoverflow.com/questions/9025027/data-hiding-in-python-class) – Peter Wood Mar 29 '16 at 21:46
  • anonymous namespaces around c++ class definitions in `.cc` files aren't to prevent the class from being used outside that TU (it already can't be). It's to prevent ODR-violations if the same class name is used in another TU with a different class definition. – Ryan Haining Mar 29 '16 at 23:07

2 Answers2

3
class MyClassOuter:
    def __init__(self,...):
        class MyClassInner:
              def __init__(self,...):
                 pass
        self.my_class = MyClassInner(..)

would only have MyClassInner available inside the __init__ function of MyClassOuter

likewise you could put it inside a function

def my_class_factory(arg1,arg2,...):
    class MyClass:
        def __init__(self,arg1,arg2,...):
           print "OK??"
    return MyClass(arg1,arg2,...)
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
1

Python code doesn't have any such equivalent for an anonymous namespace, or static linkage for functions. There are a few ways you can get what you're looking for

  1. Prefix with _. Names beginning with an underscore are understood to be for internal use to that python file and are not exported by from * imports. it's as simple as class _MyClass.
  2. Use __all__: If a python file contains a list a list of strings named __all__, the functions and classes named within are understood to be local to that python file and are not exported by from *.
  3. Use local classes/functions. This would be done the same way you've done so with C++ classes.

None these gets exactly what you want, but privacy and restricting in this way are just not part of the language (much like how there's no private data member equivalent). Pydoc is also well aware of these conventions and will provide informative documentation for the intended-to-be-public functions and classes.

tijko
  • 7,599
  • 11
  • 44
  • 64
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174