Encapsulation in Python

Rick Johnson rantingrickjohnson at gmail.com
Sat Mar 12 11:49:19 EST 2016


On Friday, March 11, 2016 at 6:52:42 PM UTC-6, Gregory Ewing wrote:
> Rick Johnson wrote:
> > I have witnessed the mayhem that occurs when a language does
> > not mandate module encapsulation (Ruby, i'm looking directly
> > at you!!!!), and while i agree with the Python designers
> > that modules must *ALWAYS* be mandatory, i am not convinced
> > that module space should be so strictly confined to source
> > files.
> 
> Well, I am. When looking at someone else's code, it's
> very useful to be able to take a name used in one source
> file and easily find the file where it's defined. That's
> very easy to do in Python, and very hard to do in languages
> that don't relate namespaces and source files.

You're essentially saying that all you have to do is scroll
up to the top of the current file, and find the line that
imports the symbol, and that line will tell you the name of
the module that contains the source code for that symbol.

Sure, that's reliable in most cases, but your argument
assumes that the actual source code for the symbol exists in
the module from which it was imported, when it could just as
well exist N-levels below that that module, due to chained
imports. 

Imagine this scenario:

    ####################
    # currentModule.py #
    ####################
    from modX import foo
    
    def bar():
        return foo()
    
    ###########
    # modX.py #
    ###########
    from modY import foo
    
    ###########
    # modY.py #
    ###########
    from modZ import foo
    
    ###########
    # modZ.py #
    ###########
    def foo():
        return 'O:-)'

I'll admit this is a highly contrived example, but it is not
invalid in anyway, and could therefore exist in reality. So
even though you will *EVENTUALLY* find the source code for
"foo", you would have to follow a long chain of imports to
get there. A more efficient method of finding the source,
would be to search your library for "def foo(", or, even
better, to utilize the tools available in the stdlib.

    PY> import Tkinter as tk
    PY> import inspect
    PY> inspect.getsourcefile(tk.Frame)
    C:\Python27\lib\lib-tk\Tkinter.py

Your editor should have tools for doing both of these
searches, and, if it's worth it's weight in salt, it will
even open the file for you. 



More information about the Python-list mailing list