Besides performance (read here[1]), the following is what I miss in Python the most as a C++ coder:
1. Scoped resources. Compare C++
- void handle_request(Request r) {
- Transaction t(db_);
- // Construct queries, specify data sinks, etc.
- }
with Python
- def handle_request(r):
- t = Transaction(self._db)
- try:
- # Construct queries, specify data sinks, etc.
- t.commit()
- finally:
- t.rollback()
In the C++ snippet the transaction is properly finalised regardless of anything. Moreover, you can’t forget it, the language performs that for you. In Python you have to remember to handle commit/rollback situation manually. There is the “with” construct which saves some typing, but is still optional.
- def handle_request(r):
- t = Transaction(self._db)
- with t:
- # Construct queries, specify data sinks, etc.
- t.commit()
2. Scope resolution.
This is purely a readability problem, but in Python I have to prepend many names with “self.”, even class-level constants:
- def indicate_error(self):
- self.leds.set_color(self.LEFT, self.YELLOW, 0.5)
- self.leds.set_color(self.RIGHT, self.YELLOW, 0.5)
The C++ version would be:
- void indicate_error() {
- leds.set_color(LEFT, YELLOW, 0.5);
- leds.set_color(RIGHT, YELLOW, 0.5);
- }
I guess this is a part of “explicit is better than implicit” mantra, but if any Python experts know an elegant solution (not involving global variables), I’d appreciate the advice.
3. Annotation of immutability.
C++ features “const-correctness” that neatly expresses the command-query separation[2]. Note that this usage of “const” is only distantly related to constants[3].
- class Change {
- public:
- Cost estimate() const;
- void prepare();
- };
- void transfigure(const Change& c);
For a C++ programmer it is obvious that transfigure() may call estimate(), but not prepare(). Furthermore, any functions invoked from within transfigure() must obey this rule. This is very unobvious with Python:
- class Change:
- def estimate(self):
- # some code
- def prepare(self):
- # some code
- def transfigure(c):
- # some more code
4. Value types.
This is what gives idiomatic C++ programs so much of their relative simplicity!
- struct Money {
- std::string currency;
- int cents;
- };
- Money a = estimate_price();
- register_price("ball", a);
- a.cents += 2; // This does not change the price of the ball.
- register_price("doll", a);
In the snippet above it is the current value of the variable a that is passed to the register_price() functions, not a reference to the variable itself. Therefore changes to the variable that happen after the call have no effect on the already registered prices.
Compare with Python:
- class Money:
- def __init__(self):
- self.currency = "EUR"
- self.cents = 0
- a = estimate_price()
- register_price("ball", a)
- a.cents = a.cents + 2 # The price of the ball might change!
- register_price("doll", a)
Obviously, it is possible to write this kind of programs in Python, but that requires some thinking and IMHO the problem does not worth the effort.
5. Static typing.
If the program at hand is sufficiently big I find myself hunting class definitions. Code for context:
- def compute(m):
- metric_data = m.fetch()
- use(how_am_i_supposed_to_use_metric_data_here)
- # The proper incantation looks like this:
- use(metric_data[“Cost”].data_points[0][“value”])
I normally spend significant time to figure that it is legal to access “data_points” and the number of indexing operators to use.
Compare with C++:
- Stats compute(Monitor *m) {
- MetricData data = m->fetch();
- use(/* How to use data? */);
- }
Go to the definition of Monitor (in many cases that’s a click), then TimeSeries. I see the indexer on MetricData returns a reference to TimeSeries which is an array of maps, indexed by strings. Bingo!
- class MetricData {
- public:
- const TimeSeries& operator[](const std::string& name) const;
- };
- struct TimeSeries {
- std::vector<std::map<std::string, double>> data_points;
- };
Finally, I must admit that while I have substantial experience with C++ I am only a casual user of Python, so any corrections are welcome!
>> Also you can read: What are some hidden features of Python
أضف تعليق:
0 comments: