Python module attributes list

Python Module Attributes: name, doc, file, dict

Python module has its attributes that describes it. Attributes perform some tasks or contain some information about the module. Some of the important attributes are explained below:

__name__ Attribute

The __name__ attribute returns the name of the module. By default, the name of the file (excluding the extension .py) is the value of __name__attribute.

import math print(math.__name__) #'math' 

In the same way, it gives the name of your custom module e.g. calc module will return ‘calc’.

import calc print(calc.__name__) #'calc' 

However, this can be modified by assigning different strings to this attribute. Change hello.py as shown below.

def SayHello(name): print ("Hi <>! How are you?".format(name)) __name__="SayHello" 

And check the __name__ attribute now.

import hello print(hello.__name__) #'SayHello'

The value of the __name__ attribute is __main__ on the Python interactive shell and in the main.py module.

When we run any Python script (i.e. a module), its __name__ attribute is also set to __main__ . For example, create the following welcome.py in IDLE.

Читайте также:  Trace java exception has occurred

Run the above welcome.py in IDLE by pressing F5. You will see the following result.

However, when this module is imported, its __name__ is set to its filename. Now, import the welcome module in the new file test.py with the following content.

import welcome print("__name__ = ", __name__) 

Now run the test.py in IDLE by pressing F5. The __name__ attribute is now «welcome».

This attribute allows a Python script to be used as an executable or as a module.

Visit __main__ in Python for more information.

__doc__ Attribute

The __doc__ attribute denotes the documentation string (docstring) line written in a module code.

import math print(math.__doc__) 

Consider the the following script is saved as greet.py module.

"""This is docstring of test module""" def SayHello(name): print ("Hi <>! How are you?".format(name)) return 

The __doc__ attribute will return a string defined at the beginning of the module code.

import greet print(greet.__doc__) 

__file__ Attribute

__file__ is an optional attribute which holds the name and path of the module file from which it is loaded.

import io print(io.__file__) #output: 'C:\\python37\\lib\\io.py' 

__dict__ Attribute

The __dict__ attribute will return a dictionary object of module attributes, functions and other definitions and their respective values.

import math print(math.__dict__) 

The dir() is a built-in function that also returns the list of all attributes and functions in a module.

You can use the dir() function in IDLE too, as shown below.

Источник

How To List All Python Module Functions And Attributes By Module Name

After you import a python module object by name in python source code dynamically ( How To Load / Import Python Package, Module Dynamically ), you must want to get all the module object attributes or functions. Then you can invoke the related module function or attributes in source code. This article will show you how to do it.

1. How To List All Functions Or Attributes Of Imported Python Module Steps.

  1. You can use python built-in dir(module_object) function to return all the module members include both function and attributes.
  2. You can also use python inspect module’s getmembers(module_object) function to get all module members, then use inspect module’s isfunction(object) function to check whether the module member is a function or not.
  3. Below is the example code, please see code comments for detail.
# Import getmembers, isfunction function from inspect module. from inspect import getmembers, isfunction # This function will list all the functions and attributes of the module. def list_module_attributes(mod_name): # First import the module object by module name. imported_module = __import__(mod_name, globals=None, locals=None, fromlist=True) # The dir() function will return all attributes and functions of the module object. mod_attrs_str = dir(imported_module) print(mod_attrs_str) ''' The inspect.getmembers() function will get all members of the module object. The inspect.isfunction() function will check whether the module member is a function or not. Below code will return module functions only. ''' functions_list = [o for o in getmembers(imported_module) if isfunction(o[1])] # Each element in the functions_list is a tuple object. for func in functions_list: # The first element of the tuple is the function name. print(func[0]) if __name__ == '__main__': list_module_attributes('lib.mod1')

Below is above example output.

['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'method_1', 'method_2'] method_1 method_2

Источник

Python module attributes list

Last updated: Feb 22, 2023
Reading time · 3 min

banner

# Table of Contents

# Get all attributes of an Object in Python

Use the dir() function to get all attributes of an object, e.g. print(dir(object)) .

The dir function will return a list of the valid attributes of the provided object.

Copied!
class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # 👇️ print(bobby.__dict__) # ------------------------------- attributes = list(bobby.__dict__.keys()) print(attributes) # 👉️ ['first', 'last', 'age'] # ------------------------------- # ['__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', 'first', 'last'] print(dir(bobby))

get all attributes of an object

The dir function takes an object and returns a list containing the object’s attributes.

If you pass a class to the function, it returns a list of the names of the class’s attributes, and recursively of the attribute of its base classes.

# Pretty print the object’s attributes using pprint()

If you need to pretty print the attributes of the object, use the pprint() method.

Copied!
from pprint import pprint class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # ['__class__', # '__delattr__', # '__dict__', # '__dir__', # '__doc__', # . # ] pprint(dir(bobby))

pretty print object attributes using pprint

The pprint.pprint method prints the formatted representation of an object.

# Get each attribute and its value

If you need to get each attribute and its value, use the getattr() function.

Copied!
class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) for attribute in dir(bobby): print(attribute, getattr(bobby, attribute))

The getattr function returns the value of the provided attribute of the object.

The function takes the object, the name of the attribute and a default value for when the attribute doesn’t exist on the object as parameters.

# Get an object’s properties and values using __dict__

If you need to get an object’s properties and values, use the __dict__ attribute.

Copied!
class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # 👇️ print(bobby.__dict__) # ------------------------------- attributes = list(bobby.__dict__.keys()) print(attributes) # 👉️ ['first', 'last', 'age'] # ------------------------------- values = list(bobby.__dict__.values()) print(values) # 👉️ ['bobby', 'hadz', 30]

get object properties and values using dict

You can use the dict.keys() and dict.values() methods if you only need the object’s attribute or values.

# Format the object’s attributes into a string

If you need to format the object’s attributes into a string, use the str.join() method and a formatted string literal.

Copied!
class Person(): def __init__(self, first, last, age): self.first = first self.last = last self.age = age bobby = Person('bobby', 'hadz', 30) # 👇️ dict_items([('first', 'bobby'), ('last', 'hadz'), ('age', 30)]) print(bobby.__dict__.items()) result = ', '.join(f'key>=str(value)>' for key, value in bobby.__dict__.items()) print(result) # 👉️ first=bobby, last=hadz, age=30

format object attributes into string

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .

Copied!
var1 = 'bobby' var2 = 'hadz' result = f'var1>var2>' print(result) # 👉️ bobbyhadz

Make sure to wrap expressions in curly braces — .

# Get an object’s attributes using vars()

Alternatively, you can use vars() .

The vars() function returns a dictionary containing the object’s properties and values.

Copied!
class Employee(): def __init__(self, id, name, salary): self.id = id self.name = name self.salary = salary bob = Employee(1, 'bobbyhadz', 100) # 👇️ print(vars(bob)) only_attributes = list(vars(bob).keys()) print(only_attributes) # 👉️ ['id', 'name', 'salary'] only_values = list(vars(bob).values()) print(only_values) # 👉️ [1, 'bobbyhadz', 100]

get object attributes using vars

The vars function takes an object and returns the __dict__ attribute of the given module, class, instance or any other object that has a __dict__ attribute.

The vars() function raises a TypeError if the provided object doesn’t have a __dict__ attribute.

Which approach you pick is a matter of personal preference. I’d use the __dict__ attribute directly to be more explicit.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью