Part of the common wisdom among some OO fanatics is that Python isn't a real OO language because it "doesn't have encapsulation." There are a few different things that could mean, but none of them say anything useful.

Python facilitates and encourages bundling data together with methods that work on that data, in the exact same way that Smalltalk, C++, and their descendants do (and equivalent way to what other OO paradigms like Self-style prototypes). This is really the only useful definition of "encapsulation", and in this sense, Python does have encapsulation.

The fact that Python's idiom doesn't encourage getters and setters is irrelevant, because getters and setters just provide a different way of spelling attribute access, and one which (except in the case of syntactically restricted languages like C++) adds no flexibility, future-proofing, or other benefits.

The fact that Python's _-prefix idiom doesn't actually hide or protect private variables is true, but the same is true for almost every other paradigm OO language. So, if you want to define encapsulation in these terms, then no, Python is not a good encapsulating OO language—and neither is Smalltalk, C#, Ruby, JavaScript, …

Hidden internal state

One definition of encapsulation is that the data members of an object should not be visible.

The C++ family (including Java and C#), Objective C, even Eiffel have the full list of the data members visible in the source. And in most of those languages, the header file or other "interface" that you distribute with a compiled module includes them as well.

But at least they hide that list at runtime, right? Well, if you look at most of the OO languages with any kind of reflection—Ruby, Java, etc.—no, no they don't. And in languages without reflection, like C++, the methods are just as hidden as the members.

In fact, this kind of "encapsulation" does exist, and is used frequently, in non-OO languages like C and Lisp: Just pass around an opaque, untyped, meaningless handle instead of a reference to an actual object. This can be a void*-cast pointer to an object whose type isn't defined anywhere in the headers you distribute (like a Win32 HANDLE), or it can be a key into some table that you maintain inside your library (like a POSIX file descriptor). And of course you can do this in Java or Eiffel or Python as well (in fact, slightly more easily in Python than in most languages, because it has a built-in mapping type to use for that table), but I don't think that makes it an OO feature.

(In C++, there's an idiom ("pimpl") that wraps up this kind of handle in an OO interface. And this same idiom works in Python, it's just not very common. But that just puts Python in the same class of languages as Java, Ruby, Eiffel, ObjC, etc.)

Restricted access

So forget about actually hiding information, what about restricting access to it?

In C++ and friends, you can mark an attribute as "private". Python's equivalent is to prefix the attribute name with an "_".

Python's "_" doesn't actually stop you from accessing the attribute from outside, it just discourages you. It's a clear signal to the user of your class that he shouldn't be using this attribute, that it could disappear or change meaning in future versions, etc. (It also prevents the attribute from showing up in various kinds of reflection, but you can always get around that with other kinds of reflection—e.g., in IPython or various IDEs, private names aren't be offered as a completion, unless someone first types a _ to see them.) This is pretty closely equivalent to the POSIX notion of "hidden files" with a "." prefix, as opposed to, say, MacOS or Windows actual hidden files.

But then very few other languages actually stop you from accessing the attribute either. This protection effectively comes from static type checking, and almost all statically-typed OO languages either have leaky type systems, or inflexible type systems that need (and have) escape hatches. For example, in C++, you can always cast through void* to char* and get at the structure members. Or, even simpler, define a class with identical but all-public structure and just cast to that. (Of course it's easier to do that to a C++ class from Python via ctypes or Cython than from C++, but that doesn't actually speak well of C++'s "protection" of its private members.) Just as with, say, MacOS or Windows actual hidden files, there are flags to pass to allow access to the hidden files if you want it.

If you build an object system on top of, say, Haskell, it can actually prevent access in ways that these languages can't. But the fact that few if any OO languages have static strong typing, and people who use strongly-typed languages like Haskell tend to see only limited use for OO, implies that this kind of restricted access is not an OO feature, any more than access through opaque tokens is.

Sandboxing

Java (and, to an extent, C#) tries to restrict access further than C++, despite providing more reflection, by effectively making the static protection information available at load time (and attempting to make that secure even for code from different sources, in Java's case) and then running the entire program inside a sandbox that can cover holes in the leaky type system.

If someone really wanted to argue that this means Java (modulo design flaws or JVM implementation bugs) is OO in a way that Eiffel, Ruby, Smalltalk, etc. are not, I suppose that would count as a way that Python isn't OO either. But that doesn't seem like a very useful distinction.

Getters and setters

The standard idiom in most "encapsulated" OO languages is to provide "getter" and "setter" methods for every data attribute. Some, like C# and Eiffel, have ways to automate that for you. Not only does Python have no way to automate this, the idiom explicitly discourages this kind of design.

But using ubiquitous getters and setters means the data members are conceptually not hidden at all. They add absolutely nothing. What Python idiomatically spells as "foo.spam" and "foo.spam = eggs" is exactly the same thing C# idiomatically spells "foo.GetSpam()" and "foo.SetSpam(eggs)". The spam attribute is idiomatically visible in both languages.

Of course getters and setters have an advantage: you can later decide to replace the real attribute with a virtual, computed attribute; just change the getter and setter and your API is unchanged.

But that isn't necessary in Python—or even in C#, ObjC, and similar languages. You can always just replace the real attribute with a @property, and the API is unchanged, but now it's accessing a virtual, computed attribute. (Or, of course, you can always intercept access via __getattr__ and friends…)

Bundling data and methods

Another common definition of encapsulation is that it facilitates bundling data together with the methods that work on that data.

There's really nothing objectionable about that definition. 

And it applies perfectly well to the class notion in C++, Java, C#, Eiffel, Sather, Smalltalk, ObjC, Ruby, etc.—and in Python. (And the prototype notion in Self or JavaScript, etc.)

This is something that you don't get from C or Lisp—you have to build encapsulation manually, and use project-specific naming conventions, header-file layouts, documentation, etc. to expose the API you want to the user—while in OO languages, there's a construct that makes it easy to build and self-documenting.

So, in the most useful sense of the word, Python does have encapsulation. And in every other sense where it doesn't, neither do any of the languages it's compared to do.
3

View comments

It's been more than a decade since Typical Programmer Greg Jorgensen taught the word about Abject-Oriented Programming.

Much of what he said still applies, but other things have changed. Languages in the Abject-Oriented space have been borrowing ideas from another paradigm entirely—and then everyone realized that languages like Python, Ruby, and JavaScript had been doing it for years and just hadn't noticed (because these languages do not require you to declare what you're doing, or even to know what you're doing). Meanwhile, new hybrid languages borrow freely from both paradigms.

This other paradigm—which is actually older, but was largely constrained to university basements until recent years—is called Functional Addiction.

A Functional Addict is someone who regularly gets higher-order—sometimes they may even exhibit dependent types—but still manages to retain a job.

Retaining a job is of course the goal of all programming. This is why some of these new hybrid languages, like Rust, check all borrowing, from both paradigms, so extensively that you can make regular progress for months without ever successfully compiling your code, and your managers will appreciate that progress. After all, once it does compile, it will definitely work.

Closures

It's long been known that Closures are dual to Encapsulation.

As Abject-Oriented Programming explained, Encapsulation involves making all of your variables public, and ideally global, to let the rest of the code decide what should and shouldn't be private.

Closures, by contrast, are a way of referring to variables from outer scopes. And there is no scope more outer than global.

Immutability

One of the reasons Functional Addiction has become popular in recent years is that to truly take advantage of multi-core systems, you need immutable data, sometimes also called persistent data.

Instead of mutating a function to fix a bug, you should always make a new copy of that function. For example:

function getCustName(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

When you discover that you actually wanted fields 2 and 3 rather than 1 and 2, it might be tempting to mutate the state of this function. But doing so is dangerous. The right answer is to make a copy, and then try to remember to use the copy instead of the original:

function getCustName(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

function getCustName2(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[2] + ' ' + custRec[3];
    return fullname;
}

This means anyone still using the original function can continue to reference the old code, but as soon as it's no longer needed, it will be automatically garbage collected. (Automatic garbage collection isn't free, but it can be outsourced cheaply.)

Higher-Order Functions

In traditional Abject-Oriented Programming, you are required to give each function a name. But over time, the name of the function may drift away from what it actually does, making it as misleading as comments. Experience has shown that people will only keep once copy of their information up to date, and the CHANGES.TXT file is the right place for that.

Higher-Order Functions can solve this problem:

function []Functions = [
    lambda(custID) {
        custRec = readFromDB("customer", custID);
        fullname = custRec[1] + ' ' + custRec[2];
        return fullname;
    },
    lambda(custID) {
        custRec = readFromDB("customer", custID);
        fullname = custRec[2] + ' ' + custRec[3];
        return fullname;
    },
]

Now you can refer to this functions by order, so there's no need for names.

Parametric Polymorphism

Traditional languages offer Abject-Oriented Polymorphism and Ad-Hoc Polymorphism (also known as Overloading), but better languages also offer Parametric Polymorphism.

The key to Parametric Polymorphism is that the type of the output can be determined from the type of the inputs via Algebra. For example:

function getCustData(custId, x)
{
    if (x == int(x)) {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return int(fullname);
    } else if (x.real == 0) {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return double(fullname);
    } else {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return complex(fullname);
    }
}

Notice that we've called the variable x. This is how you know you're using Algebraic Data Types. The names y, z, and sometimes w are also Algebraic.

Type Inference

Languages that enable Functional Addiction often feature Type Inference. This means that the compiler can infer your typing without you having to be explicit:


function getCustName(custID)
{
    // WARNING: Make sure the DB is locked here or
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

We didn't specify what will happen if the DB is not locked. And that's fine, because the compiler will figure it out and insert code that corrupts the data, without us needing to tell it to!

By contrast, most Abject-Oriented languages are either nominally typed—meaning that you give names to all of your types instead of meanings—or dynamically typed—meaning that your variables are all unique individuals that can accomplish anything if they try.

Memoization

Memoization means caching the results of a function call:

function getCustName(custID)
{
    if (custID == 3) { return "John Smith"; }
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

Non-Strictness

Non-Strictness is often confused with Laziness, but in fact Laziness is just one kind of Non-Strictness. Here's an example that compares two different forms of Non-Strictness:

/****************************************
*
* TO DO:
*
* get tax rate for the customer state
* eventually from some table
*
****************************************/
// function lazyTaxRate(custId) {}

function callByNameTextRate(custId)
{
    /****************************************
    *
    * TO DO:
    *
    * get tax rate for the customer state
    * eventually from some table
    *
    ****************************************/
}

Both are Non-Strict, but the second one forces the compiler to actually compile the function just so we can Call it By Name. This causes code bloat. The Lazy version will be smaller and faster. Plus, Lazy programming allows us to create infinite recursion without making the program hang:

/****************************************
*
* TO DO:
*
* get tax rate for the customer state
* eventually from some table
*
****************************************/
// function lazyTaxRateRecursive(custId) { lazyTaxRateRecursive(custId); }

Laziness is often combined with Memoization:

function getCustName(custID)
{
    // if (custID == 3) { return "John Smith"; }
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

Outside the world of Functional Addicts, this same technique is often called Test-Driven Development. If enough tests can be embedded in the code to achieve 100% coverage, or at least a decent amount, your code is guaranteed to be safe. But because the tests are not compiled and executed in the normal run, or indeed ever, they don't affect performance or correctness.

Conclusion

Many people claim that the days of Abject-Oriented Programming are over. But this is pure hype. Functional Addiction and Abject Orientation are not actually at odds with each other, but instead complement each other.
5

View comments

Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.