Writing efficient and concise code starts with a solid understanding of programming fundamentals and ends with mastering the syntax, structure, and idioms of a specific language. Idiomatic code is easy for other programmers to understand and recognize patterns in, making it a valuable tool for any developer.
As programming languages evolve, so do the best practices and idioms. In Python, for example, the way to read a file has changed over time. An old, anti-pattern way of reading a file would be:
_FILE = "data/pears.png"
# anti-pattern š«
f = open(_FILE, mode="rb")
img_bytes = f.read()
# do awesome things
f.close()
This way of reading a file is considered an anti-pattern because it doesn't ensure that the file is properly closed. A better way to read a file would be:
# O.K. Meh š
try:
f = open(_FILE, mode="rb")
img_bytes = f.read()
# do something awesome
finally:
f.close()
Even better would be to use the with statement:
# better š
with open(_FILE, mode="rb") as f:
img_bytes = f.read()
# do something awesome
Or even better yet, using the Path class from pathlib
:
# awesomeness š¤
from pathlib import Path
img_bytes = Path(_FILE).read_bytes()
# do something awesome
By staying up-to-date with the latest idioms and best practices, you can write code that is more efficient, concise, and easy to read for other programmers. Keep learning, keep experimenting, and keep writing idiomatic code.
Until then, keep on coding, idiomatically!
Top comments (0)