If you've migrated to Python from C++ or one of its descendants (Java, C#, D, etc.), or to a lesser extent from other OO languages (Objective C, Ruby, etc.), the first time you asked for help on StackOverflow or CodeReview or python-list or anywhere else, the first response you got was probably: "Get rid of those getters and setters."

If you asked why, you probably got no more of an answer than "You don't need them in Python."

That's exactly the response you should get—but that doesn't mean it's a bad question, just that SO is the wrong place to answer it (especially in comments).

To answer the question, we have to look at why getters and setters are idiomatic in those other languages, and see why the same idioms aren't appropriate in Python.

Encapsulation

The first reason you're usually given for using getters and setters is "for encapsulation: consumers of your class shouldn't even know that it has an attribute x, much less be able to change it willy-nilly." 

As an argument for getters and setters, this is nonsense. (And the people who write the C++ standard agree, but they can't stop people from writing misleading textbooks or tutorials.) Consumers of your class do know that you have an attribute x, and can change it willy-nilly, because you have a method named set_x. That's the conventional and idiomatic name for a setter for the x attribute, and it would be highly confusing to have a method with that name that did anything else.

The point of encapsulation is that the class's interface should be based on what the class does, not on what its state is. If what it does is just represent a point with x and y values, then the x and y attributes themselves are meaningful, and a getter and setter don't make them any more meaningful. If what it does is fetch a URL, parse the resulting JSON, fetch all referenced documents, and index them, then the HTTP connection pool is not meaningful, and a getter and setter don't make it any more meaningful. Adding a getter and setter almost never improves encapsulation in any meaningful way.

Computed properties

"Almost always" isn't "always". Say what your class does is represent a point more abstractly, with x, y, r, and theta values. Maybe x and y are attributes, maybe they're computed on the fly from r and theta. Or maybe they're sometimes stored as attributes, sometimes computed, depending on how you constructed or most recently set the instance. 

In that case, you obviously do need getters and setters—not to hide the x and y attributes, but to hide the fact that there may not even be any x and y attributes. 

That being said, is this really part of the interface, or just an implementation artifact? Often it's the latter. In that case, in Python (as in some C++ derived languages, like C#, but not in C++ itself), you can, and often should, still present them as attributes even if they really aren't, by using @property:

    class Point:
        @property
        def x(self):
            if self._x is None:
                self._x, self._y = Point._polar_to_rect(self._r, self._theta)
            return self.x
        @x.setter
        def x(set, value):
            if self._x is None:
                _, self._y = Point._polar_to_rect(self._r, self._theta)
            self._x = x
            self._r, self._theta = None, None
        # etc.

Lifecycle management

Sometimes, at least in C++ and traditional ObjC, even the "dumb" version of encapsulation idea isn't actually wrong, just oversimplified. Preventing people from setting your attribute by giving them a method to set your attribute is silly—but in C++, direct access to an attribute allows you to do more than just set the attribute, it allows you to store a reference to it. And, since C++ isn't garbage-collected, this means that there's nothing stopping some code from keeping that reference around after your instance goes out of scope, at which point they've now got a reference to garbage. In fact, this can be a major source of bugs in C++ code.

If you instead provide a getter or setter, you can ensure that consumers can only get a copy of the attribute. Or, if you need to provide a reference, you can hold the object by smart pointer and return a new smart pointer to the object. (Of course this means that people who—usually as a misguided attempt at optimization—write getters that return a const reference, or that return objects that aren't copy-safe, like raw pointers, are defeating the entire purpose of having getters and setters in the first place…)

This rationale, which makes perfect sense in C++, is irrelevant to Python. Python is garbage collected. And Python doesn't provide any way to take references to attributes in the first place; the only thing you can do is get a new (properly-GC-tracked) reference to the value of the attribute. If your instance goes away, but someone else is still referencing one of the values you had in an attribute, that value is still alive and perfectly usable.

Interface stability

Maybe today, you're storing x and y as attributes, but what if you want to change your implementation to compute them on the fly?

In some languages, like C++, if you're worried about that, the only option you have is to create useless getters and setters today, so that if you change the implementation tomorrow, your interface doesn't have to change.

In Python, just expose the attribute; if you change the implementation tomorrow, change the attribute to a @property, and your interface doesn't have to change.

Interface inheritance

In most languages, a subclass can change the semantics by overriding a getter and setter, but they can't do the same to a normal attribute.

Even in languages that have properties, in most cases, defining a property with the same name as a base-class attribute will not affect the base class's code—or, in many languages, even consumers of the base class's interface; all it'll do is shadow the base class's attribute with a different attribute for subclasses and direct consumers of the derived class's interface.

Also, in most languages without two-stage initialization, the derived class's code doesn't get a chance to run until the base class's initializer has finished, so it's not just difficult, but impossible, to affect how it stores its attributes.

In Python, attribute access is fully dynamic, and two-stage initialization means that __init__ methods can work downward toward the root instead of upward toward the leaf, so the answer is, again, just @property.

Design by contract

Some tutorials and textbooks explain the need for setters by arguing that you can add pre- and post-condition tests to the setter, to preserve class invariants. Which is all well and good, but every case I've ever seen, they go on to show a simple void set_x(int x) {x_ = x; } in the first example, and every subsequent one.

Needless to say, if you really are going to implement DBC today, this is just a case of "computed properties", and if you're just thinking you might want to implement it later, it's a case of "interface stability".

Read-only attributes

Sometimes, you want to expose an attribute, but make it read-only. In many languages, like C++, there's no way to do that but with a getter (and no corresponding setter). In Python, again, the answer is @property.

C++, Java, etc. also give you a way to create class-wide constants. Python doesn't really have constants, so some people try to simulate this by adding a getter. Again, though, the answer is @property. Or, consider whether you really need to enforce the fact that it's a constant. Why would someone try to change it? What would happen if they did?

Access control

C++ and most of its descendants provide three levels of access control—public is the interface to everyone, protected is additional interface for subclasses, and private is only usable by the class's own methods and its friends. Sometimes you might want to make an attribute read-only for your subclasses but writable for your own methods (or read-only for your consumers but writable for your subclasses). The only way to do this is to make the attribute private (or protected) and add a protected (or public) getter.

First, almost any OO design where this makes sense is probably not idiomatic for Python. (In fact, it's probably not even idiomatic for modern C++, but a lot of people are still programming 90s-style C++, and at any rate, it's much more idiomatic in Java. However, nobody is writing 90s-style OO in Python.) Often you can flatten out and simplify your hierarchy by passing around closures or methods, or by duck typing (that is, implicitly subtyping by just implementing the right methods, instead of subclassing); if you really do need subclassing, often you want to refactor your classes into small ABCs and/or mixins.

It's also worth noting that access control doesn't provide any actual security against malicious subclasses or consumers. (Except in Java; see below.) In ObjC, they can just ask the runtime to inspect your ivars and change them through pointers. In C++, they can't do that—but everyone using your class has to be able to see all of your members, even if they're private, as part of the header, and if they really want to force your class to do something it wouldn't normally do by changing its private members, there's nothing stopping them from reinterpret_cast<>ing their way to any part of that structure. 

At any rate, in Python, even if you wanted to control access this way, you can't do it.

Some people teach that _x is Python's equivalent of protected, and __x its equivalent of private, but that's very misleading.

The single underscore has only a conventional meaning: don't count on this being part of the useful and/or stable interface. Many introspection tools (e.g., tab completion in the interactive interface) will skip over underscore-prefixed names by default, but nothing stops a consumer from writing spam._eggs to access the value.

The double underscore mangles the name—inside your own methods, the attribute is named __x, but from anywhere else, it's named _MyClass__x. But this is not there to add any more protection—after all, _MyClass__x will still show up in dir(my_instance), and someone can still write my_instance._MyClass__x = 42. What it's there for is to prevent subclasses from accidentally shadowing your attributes or methods. (This is primarily important when the base classes and subclasses are implemented independently—you wouldn't want to add a new _spam attribute to your library and accidentally break any app that subclasses your library and adds a _spam attribute.)

Security

Java was designed to allow components that don't trust each other to run securely. That means that in some cases, access control does actually provide security. (Of course if you're just going to hide your x behind a public set_x method, that isn't adding anything…) That's great for Java, but it's irrelevant to Python, or any language without a secure class loader, etc.

Generic attributes

As far as I know, this one is really only relevant to C++ , because most other languages' generics were designed around offering most of the useful features of C++ templates without all of the mess, while C++'s templates were designed before anyone knew what they wanted to do with generics.

There are many cases where it's hard to specify a type for an attribute in a class template. C++ has much more limited type inference for classes and objects (before C++11, there was none at all) than for functions and types. Also, a class or class template can have methods that are themselves templates, but there are no "object templates", so you have to simulate them with either traits classes or function templates—that is, templated getters and setters. And there are also cases where it's hard to specify a constant or initializer value for an attribute, so again you have to simulate them with either traits classes or function templates.

Needless to say, none of these applies at all in duck-typed Python.

Libraries and tools

In some languages, there are libraries for reflection or serialization, observer-notification frameworks, code-generating wizards for UIs or network protocols, tools like IDEs and refactoring assistants, etc., that expect you to use getters and setters. This is particularly true in Java, and to a lesser extent C# and ObjC. Obviously you don't want to fight against these tools.

The tools and libraries for Python are, of course, designed around the idea that your attributes are attributes, not hidden behind getters and setters. But if you're, say, using PyObjC to write Python code that's bound to a NIB both at runtime and in InterfaceBuilder, you have to do things the way InterfaceBuilder wants you to.

Breakpoints

In some debuggers, it's impossible to place a watchpoint on a variable, or at least much harder or much less efficient than placing a breakpoint on a setter. If you expect this to be a problem, and you need to be able to debug code in the field without editing it, you might want to hide some attributes behind @property for easier debugging. But this doesn't come up very often.

Other languages

So, what if you're a Python programmer and you have to write some code in Java or D? Just as you shouldn't make your Python code look like Java, you shouldn't make your Java code look like Python. This means you'll probably want a lot more getters and setters than you're used to.

In Java, C#, D, etc. many of the same motivations (both good and bad) for getters and setters apply the same as in C++. In some cases, some of the motivations don't apply (e.g., C# has properties, just like Python; Java generics don't work like C++ templates). So there are a few cases where there are additional reasons for getters and setters.

But, more importantly, Java (and, to a lesser extent, C#, ObjC, etc.) has a much stronger culture than C++ of idiomatically requiring getters and setters even when there's no objectively good reason. There are wizards that generate them for you, linters that warn if you don't use them, IDEs that expect them to exist, coworkers or customers that complain… And the fact that it's idiomatic is in itself a good reason to follow the idiom, even if there's no objective basis for it.
8

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.

5

I haven't posted anything new in a couple years (partly because I attempted to move to a different blogging platform where I could write everything in markdown instead of HTML but got frustrated—which I may attempt again), but I've had a few private comments and emails on some of the old posts, so I

6

Looking before you leap

Python is a duck-typed language, and one where you usually trust EAFP ("Easier to Ask Forgiveness than Permission") over LBYL ("Look Before You Leap").

1

Background

Currently, CPython’s internal bytecode format stores instructions with no args as 1 byte, instructions with small args as 3 bytes, and instructions with large args as 6 bytes (actually, a 3-byte EXTENDED_ARG followed by a 3-byte real instruction).

6

If you want to skip all the tl;dr and cut to the chase, jump to Concrete Proposal.

8

Many people, when they first discover the heapq module, have two questions:

Why does it define a bunch of functions instead of a container type? Why don't those functions take a key or reverse parameter, like all the other sorting-related stuff in Python? Why not a type?

At the abstract level, it'

1

Currently, in CPython, if you want to process bytecode, either in C or in Python, it’s pretty complicated.

The built-in peephole optimizer has to do extra work fixing up jump targets and the line-number table, and just punts on many cases because they’re too hard to deal with.

3

One common "advanced question" on places like StackOverflow and python-list is "how do I dynamically create a function/method/class/whatever"? The standard answer is: first, some caveats about why you probably don't want to do that, and then an explanation of the various ways to do it when you reall

1

A few years ago, Cesare di Mauro created a project called WPython, a fork of CPython 2.6.4 that “brings many optimizations and refactorings”. The starting point of the project was replacing the bytecode with “wordcode”. However, there were a number of other changes on top of it.

1

Many languages have a for-each loop.

4

When the first betas for Swift came out, I was impressed by their collection design. In particular, the way it allows them to write map-style functions that are lazy (like Python 3), but still as full-featured as possible.

2

In a previous post, I explained in detail how lookup works in Python.

2

The documentation does a great job explaining how things normally get looked up, and how you can hook them.

But to understand how the hooking works, you need to go under the covers to see how that normal lookup actually happens.

When I say "Python" below, I'm mostly talking about CPython 3.5.

7

In Python (I'm mostly talking about CPython here, but other implementations do similar things), when you write the following:

def spam(x): return x+1 spam(3) What happens?

Really, it's not that complicated, but there's no documentation anywhere that puts it all together.

2

I've seen a number of people ask why, if you can have arbitrary-sized integers that do everything exactly, you can't do the same thing with floats, avoiding all the rounding problems that they keep running into.

2

In a recent thread on python-ideas, Stephan Sahm suggested, in effect, changing the method resolution order (MRO) from C3-linearization to a simple depth-first search a la old-school Python or C++.

1

Note: This post doesn't talk about Python that much, except as a point of comparison for JavaScript.

Most object-oriented languages out there, including Python, are class-based. But JavaScript is instead prototype-based.

1

About a year and a half ago, I wrote a blog post on the idea of adding pattern matching to Python.

I finally got around to playing with Scala semi-seriously, and I realized that they pretty much solved the same problem, in a pretty similar way to my straw man proposal, and it works great.

About a year ago, Jules Jacobs wrote a series (part 1 and part 2, with part 3 still forthcoming) on the best collections library design.

1

In three separate discussions on the Python mailing lists this month, people have objected to some design because it leaks something into the enclosing scope. But "leaks into the enclosing scope" isn't a real problem.

2

There's a lot of confusion about what the various kinds of things you can iterate over in Python. I'll attempt to collect definitions for all of the relevant terms, and provide examples, here, so I don't have to go over the same discussions in the same circles every time.

8

Python has a whole hierarchy of collection-related abstract types, described in the collections.abc module in the standard library. But there are two key, prototypical kinds. Iterators are one-shot, used for a single forward traversal, and usually lazy, generating each value on the fly as requested.

2

There are a lot of novice questions on optimizing NumPy code on StackOverflow, that make a lot of the same mistakes. I'll try to cover them all here.

What does NumPy speed up?

Let's look at some Python code that does some computation element-wise on two lists of lists.

2

When asyncio was first proposed, many people (not so much on python-ideas, where Guido first suggested it, but on external blogs) had the same reaction: Doing the core reactor loop in Python is going to be way too slow. Something based on libev, like gevent, is inherently going to be much faster.

Let's say you have a good idea for a change to Python.

1

There are hundreds of questions on StackOverflow that all ask variations of the same thing. Paraphrasing:

lst is a list of strings and numbers. I want to convert the numbers to int but leave the strings alone.

2

In Haskell, you can section infix operators. This is a simple form of partial evaluation. Using Python syntax, the following are equivalent:

(2*) lambda x: 2*x (*2) lambda x: x*2 (*) lambda x, y: x*y So, can we do the same in Python?

Grammar

The first form, (2*), is unambiguous.

1

Many people—especially people coming from Java—think that using try/except is "inelegant", or "inefficient". Or, slightly less meaninglessly, they think that "exceptions should only be for errors, not for normal flow control".

These people are not going to be happy with Python.

2

If you look at Python tutorials and sample code, proposals for new language features, blogs like this one, talks at PyCon, etc., you'll see spam, eggs, gouda, etc. all over the place.

Most control structures in most most programming languages, including Python, are subordinating conjunctions, like "if", "while", and "except", although "with" is a preposition, and "for" is a preposition used strangely (although not as strangely as in C…).

There are two ways that some Python programmers overuse lambda. Doing this almost always mkes your code less readable, and for no corresponding benefit.

1

Some languages have a very strong idiomatic style—in Python, Haskell, or Swift, the same code by two different programmers is likely to look a lot more similar than in Perl, Lisp, or C++.

There's an advantage to this—and, in particular, an advantage to you sticking to those idioms.

1

Python doesn't have a way to clone generators.

At least for a lot of simple cases, however, it's pretty obvious what cloning them should do, and being able to do so would be handy. But for a lot of other cases, it's not at all obvious.

5

Every time someone has a good idea, they believe it should be in the stdlib. After all, it's useful to many people, and what's the harm? But of course there is a harm.

3

This confuses every Python developer the first time they see it—even if they're pretty experienced by the time they see it:

>>> t = ([], []) >>> t[0] += [1] --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <stdin> in <module>()

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