How to Elegant Coding in Python

How to Elegant Coding in Python

  • 2041

How to Elegant Coding in Python .Typically, aesthetic programming was not a critical issue when we were studying in school. Individuals then follow their style when writing in Python. However, the work may be quite undesirable whenever we have to spend most of the time understanding one’s implicit code

Typically, aesthetic programming was not a critical issue when we were studying in school. Individuals then follow their style when writing in Python. However, the work may be quite undesirable whenever we have to spend most of the time understanding one’s implicit code, which could also happen to others when reading our code. Therefore, let’s focus on the Zen of Python and some improvement tips to solve the problem.

The Zen of Python?

For those who haven’t seen it before, type and execute import this in your Python interpreter, and 19 guiding principles penned by Tim Peters will show up:

  1. Beautiful is better than ugly.
  2. Explicit is better than implicit.
  3. Simple is better than complex.
  4. Complex is better than complicated.
  5. Flat is better than nested.
  6. Sparse is better than dense.
  7. Readability counts.
  8. Special cases aren’t special enough to break the rules.
  9. Although practicality beats purity.
  10. Errors should never pass silently.
  11. Unless explicitly silenced.
  12. In the face of ambiguity, refuse the temptation to guess.
  13. There should be one — and preferably only one — obvious way to do it.
  14. Although that way may not be obvious at first unless you’re Dutch.
  15. Now is better than never.
  16. Although never is often better than right now.
  17. If the implementation is hard to explain, it’s a bad idea.
  18. If the implementation is easy to explain, it may be a good idea.
  19. Namespaces are one honking great idea — let’s do more of those!

In this piece, I’m going to share my interpretation of these aphorisms and some useful Python tips I’ve learned.

This is image title

Photo by June Wong on Unsplash.

Beautiful Is Better Than Ugly

Python features simple syntax, code readability, and English-like commands that make coding a lot easier and more efficient than with other programming languages. For example, using or and vs. || &&to construct the same expressions in semantic perspective**:**

# &&, ||
if a == 0 && b == 1 || c == Ture:
  
# and, or
if a == 0 and b == 1 or c == Ture:
  
# These are the same logical expression in Python
# The alternative operators can be used to construct the exact same expressions from a semantic perspective.

alternative_operator.py

Furthermore, the layout and composition of the code are crucial, and there are plenty of resources that exist covering this topic. Here is the most popular and my favorite one:

https://www.python.org/dev/peps/pep-0008/

After looking through PEP8, take a look at these articles showing some highlights and applications:

Never mess up your code. Be elegant and make it beautiful.

Explicit Is Better Than Implicit

In Python, a good naming convention not only prevents you from getting bad grades in classes but also makes your code explicit. Fortunately, there are some guidelines you can find in PEP8, and I would like to highlight some points below.

  • In general, avoid using names that are
    1. Too general, like my_list.
    2. Too wordy, like list_of_machine_learning_data_set.
    3. Too ambiguous, like “l”, “I”, “o”, “O.”
  • Package/Module names should be all lowercase.
    • One-word names are preferred.
    • When multiple words are needed, add underscores to separate them.
  • Class names should follow the UpperCaseCamelCase convention.
  • Variables\Methods\Functions should follow the lowercase convention (add underscores to separate words if needed).
  • Constant names must be fully capitalized (add underscores to separate words if needed).

Everything has to be lucid and understandable.

Simple Is Better Than Complex

“Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it’s worth it in the end because once you get there, you can move mountains.” ― Steve Jobs

A lot of times when dealing with iterators, we also need to keep a count of iterations. Python eases the task by providing a built-in function called enumerate(). Here is the immature way followed by the recommended one:

words = ['Hannibal', 'Hanny', 'Steeve']

# Novice
index = 0
for word in words:
    print(index, word)
    index += 1
    
# Pro
for index, word in enumerate(words):
    print(index, word)

enumerate.py

Another example is using the built-in zip() function, which creates an iterator that would pair elements from two or more iterables. You can use it to solve common programming problems fast and efficiently, like creating dictionaries.

subjects = ['math', 'chemistry', 'biology', 'pyhsics']
grades = ['100', '83', '90', '92']

grades_dict = dict(zip(subjects, grades))
print(grades_dict)

zip_app.py

The ability to simplify is to eliminate the unnecessary so that the necessary may speak.

Complex Is Better Than Complicated

The difference between complex and complicated is that complex is used to refer to the system level of components, while complicated refers to a high level of difficulty.

Sometimes, although we try to keep tasks simple and stupid, the result could still be nasty. In this case, optimization in programming becomes necessary, and my favorite option of learning it is working on coding challenge websites. You can view others’ solutions and even be inspired by better algorithms.

HackerRank provides a variety of levels fitting new programmers, which is outstanding for getting started. After that, try websites that are more professional, like:

https://www.coderbyte.com/challenges

https://www.topcoder.com/challenges/?pageIndex=1

Flat Is Better Than Nested

Nested modules are not common in Python—at least I haven’t seen anything like module.class.subclass.function before—and not easy to read. Though building a submodule in another submodule may reduce lines of code, we don’t want users to get troubled with unintuitive syntax.

This is image title

Sparse Is Better Than Dense

Don’t stress the reader by sticking too much code in one line. A recommended maximum line length is 79 characters. The limitation of the editor window width works well when using code review tools.

This is image title

Download images agiler from Unsplash using Python.

Readability Counts

Code is read more often than it’s written. Think about indentation and how much easier it is to read code, and compare the codes below:

money = 10000000
print("I earn", money, "dollars by writing on medium.")

money = 10_000_000
print(f"I earn {money} dollars by writing on medium.")

readability.py

In this case, the codes share the same result, but the last one provides more readability by using underscore placeholders and f-string. After Python 3.6 was announced, f-string started to make formatting easier and it’s more powerful when dealing with longer sentences with more variables inside.

A writer’s style should not place obstacles between his ideas and the minds of his readers.

Special Cases Aren’t Special Enough to Break the Rules

The consistency of supporting general cases is the key, so try to reorganize a cumbersome project into a simple form. For example, structure the code in classes or sort it into different files according to its functionality, even though Python doesn’t force you to do so. Since Python is a multi-paradigm programming language, a powerful approach to problem-solving is to create objects, which is known as object-oriented programming.

Object-oriented programming is a programming paradigm that organizes program structure so that attributes and behaviors can be viewed as individual objects. The benefit of it is intuitive and easy to manipulate, and many tutorials have splendidly explained the concepts. This one is my favorite:

Although Practicality Beats Purity

This aphorism is contradictory to the last one and reminds us of the balance between them.

This is image title

Errors Should Never Pass Silently

Passing errors would eventually leave implicit bugs that are even harder to figure out. Thanks to the robust error handling in Python, it is not difficult for programmers to use the tool compared with other languages.


try:
    x = int(input("Please enter an Integer: "))
except ValueError:
    print("Oops! This is not an Integer.")   
except Exception as err:
    print(err)
else:
    print('You did it! Great job!')
finally:
    print('ヽ(✿゚▽゚)ノ')
 
# 1.The code that potentially break down.
# 2.Triggered if the value error occur.
# 3.Handling error other than value error.
# 4.Execute if no error triggered.
# 5.Execute no matter the error triggered or not.

exception_handling.py

According to Python’s documentation: “Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it.”

Especially for a big project, we don’t want our code crashing after a time-consuming computation. This is why exception management is charming.

Unless Explicitly Silenced

In some situations, small bugs would not bother you. Maybe you want to catch the specific error, though. To get more details on specific error messages, I recommend reading the official Built-in Exceptions document and finding out your target.

https://docs.python.org/3/library/exceptions.html

In the Face of Ambiguity, Refuse the Temptation to Guess

“What is important is to keep learning, to enjoy challenge, and to tolerate ambiguity. In the end there are no certain answers.” ― Matina Horner

This quote is elegant and lyrical but not a good metaphor in programming. Ambiguity may refer to unclear syntax, complicated program structure, or mistakes that trigger an error message. For example, a simple mistake when using the numpy module for the first time:

import numpy as np

a = np.arange(5)
print(a < 3)
if a < 3:
    print('smaller than 3')
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

If you execute the code above, you’ll find an array of five bools in the output indicating the values under 3. Thus it’s impossible for the if statement to determine the state. The built-in .all() and .any() functions showed in the message are used for successive And/Or.

import numpy as np

a = np.array([True, True, True])
b = np.array([False, True, True])
c = np.array([False, False, False])

print(a.all())
print(a.any())

print(b.all())
print(b.any())

print(c.all())
print(c.any())

all_any_demo.py

The output shows that .all() returns True only if all of the items are True, while .any() returns True if any of the items are True.

There Should Be One — and Preferably Only One — Obvious Way to Do It

Think of why Python is described as an easy-to-learn programming language. With marvelous built-in functions/libraries and high expansibility, Python encourages programmers to write gracefully. Though there are more solutions to provide flexibility, it could spend too much time digging into the same problem.

This is image title

Although That Way May Not Be Obvious at First Unless You’re Dutch

The creator of Python, Guido van Rossum, is a Dutch programmer who makes this aphorism unarguable. You won’t claim that you know Python better than he does… at least I won’t.

Photo courtesy of Guido van Rossum on GitHub.

Now Is Better Than Never

“You may delay, but time will not, and lost time is never found again.” — Benjamin Franklin

For those who suffer from procrastination like me and are searching for change, check this out and cooperate with the panic monster.

On the other hand, another side of the aphorism is to stop you from over-planning, which is no more productive than watching Netflix.

The mutual attribute of procrastination and over-planning is that
“Nothing is done.”

Although Never Is Often Better Than Right Now

“Now is better than never” doesn’t mean that planning is useless. Writing the ideas down and setting a goal to conquer is better than doing it at the very moment. For example, I usually spend an hour every Sunday to scratch out my weekly schedule and update my plan for tomorrow right before I go to bed to check out anything that has to be put off.

This is image title

If the Implementation Is Hard to Explain, It’s a Bad Idea

Recall the idea of “Complex is better than complicated.” Usually, the complicated code means weak design—especially in high-level programming languages like Python. In some cases, however, the complexity of its domain knowledge could make implementation hard to explain, and how to optimize its lucidity matters. Here’s a guideline for structuring projects that leverages your achievement.

https://docs.python-guide.org/writing/structure/

If the Implementation Is Easy to Explain, It May Be a Good Idea

It’s programming expertise to make the design (or even people’s lives) easier while the background knowledge may be profound, and I think this is the hardest part of programming.

This is image title

Take advantage of the simplicity and readability in Python to implement crazy ideas.

Namespaces Are One Honking Great Idea — Let’s Do More of Those!

Last but not least, a namespace is a set of symbols that are used to organize objects of various kinds so that these objects may be referred to by unique names. In Python, a namespace is a system composed of:

  1. Built-in namespaces: Can be called without creating a self-defined function or importing modules such as the print() function.
  2. Global namespaces: When a user creates a class or function, a global namespace gets created.
  3. Local namespaces: The namespace inside local scopes.

This is image title
Diagram of namespace relations.

The namespace system prevents Python from conflicting between module names.

Conclusion

Thanks for reading! I hope you enjoyed it.