DEV Community

Cover image for 4 Python functions that make reading easier
Dev Write Ups
Dev Write Ups

Posted on • Updated on

4 Python functions that make reading easier

A function in Python is a block of coordinated, reusable code that is utilized to play out a solitary, related activity. Functions gives a better seclusion to your application and a serious level of code reusing.

In this post we're going to see 4 Functions that make reading Python code easier.


Globals

>>> globals()
{'__name__':'__main__', '__doc__': None, ...}
Enter fullscreen mode Exit fullscreen mode

As it name implies, the globals() function will display information of global scope. For example, if we open a Python console and input globals(), a dict including all names and values of variables in global scope will be returned.

Locals

def top_developer(): 
   name = 'DevWriteUps'
   country = 'Canada'
   print(locals())

top_developer()
# {'name':'DevWriteUps', 'country': 'Canada'}
Enter fullscreen mode Exit fullscreen mode

After understanding the globals(), locals() function is just a piece of cake. As its name implies, it will return a dict including all local names and values. By the way, if we call the local() in global scope, the result is identical to globals().

Vars

class TopDeveloper:
  def __init__(self):
   self.name = "DevWriteUps"
   self.county = "Canada"

me = TopDeveloper()
print(vars(me))
# {'name':'DevWriteUps',  'country':  'Canada'}
print(vars(me) is me.__dict__)
# true
Enter fullscreen mode Exit fullscreen mode

The vars() function will return the dict, which is a dictionary used to store an object's attributes. Its result is the same as calling the __dict__ directly.

DIR

class TopDeveloper:
  def __init__(self):
   self.name = "DevWriteUps"
   self.county = "Canada"
me = TopDeveloper()
print(dir(me))


# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'country', 'name']
Enter fullscreen mode Exit fullscreen mode

The dir() function helps us demonstrate a list of names in the corresponding scope. In fact, the dir method calls __dir__() internally.


Thank you For Reading🤩 Subscribe to our newsletter , we send it occasionally with amazing news, resources and many thing.

Top comments (3)

Collapse
 
waylonwalker profile image
Waylon Walker

These are all great things to mix in with the debugger, built into python 3.7+ as breakpoint()

Collapse
 
qoyyuum profile image
Abdul Qoyyuum

"gloabals()" ? 😂

Collapse
 
devwriteups profile image
Dev Write Ups

Glad you liked it.