avatarLiu Zuo Lin

Summary

The article provides insights into eight lesser-known features and functionalities in Python, ranging from built-in modules to debugging techniques and interactive programming with Turtle graphics.

Abstract

The article titled "8 More Things I Never Knew About Python Until Recently" delves into advanced and often overlooked aspects of the Python programming language. It introduces readers to the webbrowser module for opening web pages programmatically, the use of f-strings for more efficient debugging, and the statistics module for calculating medians and other statistical functions without relying on external libraries like NumPy. The article also highlights the fractions module for precise fractional calculations, the locals() and globals() functions for variable inspection, and the getpass module for secure password input without echoing to the console. Additionally, it discusses the special __debug__ variable that influences assert statement behavior based on the presence of the -O optimization flag during script execution. Lastly, the article encourages exploration of Python's Turtle module for creating graphics, and it concludes with an invitation for readers to support the author by subscribing to Medium or signing up for a newsletter.

Opinions

  • The author believes that many Python programmers may not be aware of certain built-in functionalities, which can simplify their coding tasks.
  • There is an emphasis on the convenience of Python's built-in modules, such as statistics, fractions, and getpass, over external libraries.
  • The author suggests that using locals() and globals() for variable inspection can be powerful, but also warns of potential side effects when modifying global or local variables using these functions.
  • The article promotes the use of the -O optimization flag and the __debug__ variable to control assert statement behavior, indicating a preference for efficient production code.
  • The author expresses enthusiasm about Python's capabilities, as demonstrated by the Turtle module's ability to create interesting graphics with minimal code.
  • The conclusion of the article implies that the content provided is valuable and that the author's work is worth supporting through Medium membership or newsletter subscription.

8 More Things I Never Knew About Python Until Recently

# 7) Password prompting in Python while hiding whatever our user types

cool art

1) We Can Programatically Open Our Browser Using Python

import webbrowser
webbrowser.open_new("https://medium.com")

Note — the webbrowser module is pre-installed, so we don’t have to install it using Pip. Running the above code opens a new tab of medium.com on whichever browser we are using.

2) Easier Way To Debug Using F-Strings

name = "rocky"
age = 4
breed = "german shepherd"
print(f"{name=} {age=} {breed=}")

The output:

name='rocky' age=4 breed='german shepherd'

Which allows us to type less stuff when we debug.

3) Python Has A Built-In Median Function

# And other statistics-related functions

from statistics import median
lis = [1, 5, 3, 4, 2]
print(median(lis))   # 3

The statistics module is a built-in module that we don’t have to install using Pip, and it contains many other statistics-related functions. I did not know about this, and have been using np.median from Numpy all this while!

4) Built-in Fractions In Python

from fractions import Fraction
x = Fraction(1/2)
print(x**2)   # 1/4

Python has built-in fractions that don’t return float numbers in the fractions module. Once again, this is part of the Python Standard Library, and we don’t need to install it using Pip.

5) locals() and globals()

The built-in globals() function allows us to check what global variables we have, and the built-in locals() function allows us to check what local variables we have in the scope of a function.

x = 1
y = 2
def test():
    z = 3
    print(globals())
    print(locals())
test()

The output:

# globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x108a30dc0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/lzl/Documents/repos/test/aa.py', '__cached__': None, 'x': 1, 'y': 2, 'test': <function test at 0x10896beb0>}
# locals()
{'z': 3}

We can even assign global/local variables using globals() and locals(). But I recommend you not to due to the potential side effects.

x = 1
def test():
    globals()["x"] = 5
test()
print(x)   # 5

6) The __debug__ Variable

# Probably the only variable we cannot reassign in Python

The __debug__ variable is a boolean value that is usually True when we run our Python script normally. However, if we run our Python script using the -O flag, __debug__ is set to False.

python3 -O yourscript.py

When __debug__ is False, assert statements are ignored.

assert 1==2

^ If we run the above code normally, we get an AssertionError. However, if we run it with the -O flag, __debug__ is set to False, and the assert statement is ignored.

7) Password prompting in Python while hiding whatever our user types

Notice how many command line interfaces eg. git, docker etc do not print your password when you type it? We can achieve the same effect in Python using the built-in getpass module.

from getpass import getpass
password = getpass()
print(password)

^ Here, when prompted for a password, I typed "abcdefg" into the command line. What I type isn’t printed due to getpass, but is stored in the variable password.

8) Turtle

import turtle
screen = turtle.getscreen()
x = turtle.Turtle()
for i in range(1000):
    x.forward(200)
    x.right(115)

Copy this code and run it on your computer. And wait for magic to happen.

Conclusion

Hope you learnt at least ONE new thing about Python after reading this!

Some Final words

If this article provided value and you wish to support me, do consider signing up for a Medium membership — It’s $5 a month, and you get unlimited access to articles on Medium. If you sign up using my link below, I’ll earn a tiny commission at zero additional cost to you.

Sign up using my link here to read unlimited Medium articles.

Get my free Ebooks: https://zlliu.co/books

I write programming articles (mainly Python) that would have probably helped the younger me a lot. Do join my email list to get notified whenever I publish.

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord. Interested in Growth Hacking? Check out Circuit.

Python
Python Programming
Python3
Recommended from ReadMedium