Bewildered student
Bewildered student

Reputation: 11

Explanation on globals(), and getattr() with (Python 3 within Jupyter Notebook)


I was looking for a way to get all the import version numbers within Jupyter's notebook, and I ran into this post. The code is working well, however, I would like to understand the globals(), and getters() part of the code.

What I understand so far is that m.name and m.version are being joined together as a string. Then for every m in globals() which referred to all the library is being printed, however, what throws me off is what's in the if statement. The getattr() returns the value of the named attribute, so in this case, it'll return the name of the library. I'm not sure if I'm understanding this correctly.("if getattr(m, '__version__', None))" )

# In[1]:
import pandas as pd
import numpy as np
import tensorflow as tf

print('\n'.join(f'{m.__name__} {m.__version__}' for m in globals().values() if getattr(m, '__version__', None)))

Output

pandas 1.1.1
numpy 1.19.1
tensorflow 2.2.0

Upvotes: 1

Views: 1727

Answers (1)

Barmar
Barmar

Reputation: 781380

globals() returns a dictionary of all the global variables. When you import a module, the module name becomes a global variable whose value is the module object.

System modules have a __version__ attribute that contains the version number of the module.

It's using getattr(m, '__version__', None) to avoid getting an error when it tries to access the __version__ attribute of objects that don't have that attribute. The third argument to getattr() is a default value to return if the attribute doesn't exist. This allows the generator to filter out all the objects that aren't modules.

Upvotes: 2

Related Questions