# Complete Guide to Module and Package Attributes
import sys
import os
import inspect
import types
import importlib
# Let's use the 'math' module as our example
import math
print("=" * 60)
print("MODULE INSPECTION ATTRIBUTES AND METHODS")
print("=" * 60)
# 1. BASIC MODULE ATTRIBUTES
print("\n1. BASIC MODULE ATTRIBUTES:")
print("-" * 30)
# __name__ - Module name
print(f"__name__: {math.__name__}")
# __file__ - Path to module file (None for built-in modules)
print(f"__file__: {math.__file__}")
# __doc__ - Module docstring
print(f"__doc__: {math.__doc__[:100]}..." if math.__doc__ else "No docstring")
# __package__ - Package name (None for top-level modules)
print(f"__package__: {math.__package__}")
# __spec__ - Module spec object
print(f"__spec__: {math.__spec__}")
# __loader__ - Module loader
print(f"__loader__: {math.__loader__}")
# __cached__ - Path to cached bytecode file
print(f"__cached__: {getattr(math, '__cached__', 'Not available')}")
# 2. CONTENT INSPECTION FUNCTIONS
print("\n2. CONTENT INSPECTION FUNCTIONS:")
print("-" * 30)
# dir() - List all attributes
print(f"dir(math) - First 10 attributes: {dir(math)[:10]}")
# vars() - Dictionary of module's namespace
print(f"vars(math) available: {type(vars(math))}")
# hasattr() - Check if attribute exists
print(f"hasattr(math, 'sqrt'): {hasattr(math, 'sqrt')}")
print(f"hasattr(math, 'nonexistent'): {hasattr(math, 'nonexistent')}")
# getattr() - Get attribute value safely
print(f"getattr(math, 'pi', 'Not found'): {getattr(math, 'pi', 'Not found')}")
print(f"getattr(math, 'nonexistent', 'Not found'): {getattr(math, 'nonexistent', 'Not found')}")
# 3. USING INSPECT MODULE
print("\n3. USING INSPECT MODULE:")
print("-" * 30)
# inspect.getmembers() - Get all members
members = inspect.getmembers(math)
print(f"Total members in math module: {len(members)}")
print(f"First 5 members: {members[:5]}")
# Get only functions
functions = inspect.getmembers(math, inspect.isfunction)
print(f"Functions in math: {len(functions)}")
print(f"Function names: {[name for name, obj in functions[:5]]}")
# Get only built-in functions
builtins = inspect.getmembers(math, inspect.isbuiltin)
print(f"Built-in functions: {len(builtins)}")
print(f"Built-in names: {[name for name, obj in builtins[:5]]}")
# Get constants/variables
constants = inspect.getmembers(math, lambda x: not callable(x))
print(f"Constants/variables: {[name for name, obj in constants]}")
# 4. CHECKING SPECIFIC TYPES
print("\n4. CHECKING SPECIFIC TYPES:")
print("-" * 30)
def categorize_attributes(module):
"""Categorize all attributes in a module."""
categories = {
'functions': [],
'builtin_functions': [],
'classes': [],
'modules': [],
'constants': [],
'other': []
}
for name in dir(module):
obj = getattr(module, name)
if inspect.isfunction(obj):
categories['functions'].append(name)
elif inspect.isbuiltin(obj):
categories['builtin_functions'].append(name)
elif inspect.isclass(obj):
categories['classes'].append(name)
elif inspect.ismodule(obj):
categories['modules'].append(name)
elif not callable(obj):
categories['constants'].append(name)
else:
categories['other'].append(name)
return categories
math_categories = categorize_attributes(math)
for category, items in math_categories.items():
print(f"{category}: {len(items)} items")
if items:
print(f" Examples: {items[:3]}")
# 5. FUNCTION/METHOD INSPECTION
print("\n5. FUNCTION/METHOD INSPECTION:")
print("-" * 30)
# inspect.signature() - Get function signature
if hasattr(math, 'pow'):
sig = inspect.signature(math.pow)
print(f"math.pow signature: {sig}")
# inspect.getdoc() - Get docstring
print(f"math.sqrt docstring: {inspect.getdoc(math.sqrt)}")
# inspect.getargspec() - Get function arguments (deprecated, use signature)
# This works for regular functions, not built-ins
def example_func(a, b=10, *args, **kwargs):
pass
print(f"example_func signature: {inspect.signature(example_func)}")
# 6. PACKAGE-SPECIFIC ATTRIBUTES
print("\n6. PACKAGE-SPECIFIC ATTRIBUTES:")
print("-" * 30)
# Let's create a simple package example
import json # This is a package
print(f"json.__name__: {json.__name__}")
print(f"json.__file__: {json.__file__}")
print(f"json.__path__: {getattr(json, '__path__', 'Not a package')}")
# For packages, __path__ contains the package directory
if hasattr(json, '__path__'):
print(f"Package path: {json.__path__}")
# 7. DYNAMIC ATTRIBUTE CHECKING
print("\n7. DYNAMIC ATTRIBUTE CHECKING:")
print("-" * 30)
def inspect_module_thoroughly(module):
"""Comprehensive module inspection."""
print(f"Inspecting module: {module.__name__}")
# Basic info
print(f" Type: {type(module)}")
print(f" File: {getattr(module, '__file__', 'Built-in')}")
print(f" Package: {getattr(module, '__package__', 'None')}")
# Count different types
all_attrs = dir(module)
public_attrs = [attr for attr in all_attrs if not attr.startswith('_')]
private_attrs = [attr for attr in all_attrs if attr.startswith('_')]
print(f" Total attributes: {len(all_attrs)}")
print(f" Public attributes: {len(public_attrs)}")
print(f" Private attributes: {len(private_attrs)}")
# Callable vs non-callable
callable_attrs = [attr for attr in all_attrs if callable(getattr(module, attr))]
non_callable_attrs = [attr for attr in all_attrs if not callable(getattr(module, attr))]
print(f" Callable attributes: {len(callable_attrs)}")
print(f" Non-callable attributes: {len(non_callable_attrs)}")
return {
'all': all_attrs,
'public': public_attrs,
'private': private_attrs,
'callable': callable_attrs,
'non_callable': non_callable_attrs
}
math_inspection = inspect_module_thoroughly(math)
# 8. CHECKING MODULE RELATIONSHIPS
print("\n8. MODULE RELATIONSHIPS:")
print("-" * 30)
# Check what modules are imported
print(f"Modules in sys.modules (first 10): {list(sys.modules.keys())[:10]}")
print(f"Is math in sys.modules? {math.__name__ in sys.modules}")
# Check module hierarchy
def get_module_hierarchy(module_name):
"""Get the hierarchy of a module."""
parts = module_name.split('.')
hierarchy = []
for i in range(len(parts)):
hierarchy.append('.'.join(parts[:i+1]))
return hierarchy
print(f"json.encoder hierarchy: {get_module_hierarchy('json.encoder')}")
# 9. ADVANCED INSPECTION TECHNIQUES
print("\n9. ADVANCED INSPECTION TECHNIQUES:")
print("-" * 30)
# Get source code (for non-built-in modules)
try:
import tempfile
source = inspect.getsource(tempfile.mktemp)
print(f"Source code available for tempfile.mktemp: {len(source)} characters")
except OSError:
print("Source code not available (built-in or compiled)")
# Get source file
try:
source_file = inspect.getsourcefile(tempfile.mktemp)
print(f"Source file: {source_file}")
except:
print("Source file not available")
# Check if it's a built-in module
def is_builtin_module(module):
"""Check if a module is built-in."""
return module.__file__ is None
print(f"Is math built-in? {is_builtin_module(math)}")
# 10. PRACTICAL UTILITY FUNCTIONS
print("\n10. PRACTICAL UTILITY FUNCTIONS:")
print("-" * 30)
def find_functions_by_name(module, pattern):
"""Find functions in a module that match a pattern."""
import re
functions = inspect.getmembers(module, inspect.isfunction)
builtins = inspect.getmembers(module, inspect.isbuiltin)
all_functions = functions + builtins
matching = []
for name, func in all_functions:
if re.search(pattern, name):
matching.append((name, func))
return matching
# Find all functions with 'log' in the name
log_functions = find_functions_by_name(math, r'log')
print(f"Functions with 'log' in name: {[name for name, func in log_functions]}")
def get_function_info(module, func_name):
"""Get detailed information about a function."""
if not hasattr(module, func_name):
return f"Function {func_name} not found in {module.__name__}"
func = getattr(module, func_name)
info = {
'name': func_name,
'type': type(func).__name__,
'callable': callable(func),
'doc': inspect.getdoc(func) or "No documentation",
'module': getattr(func, '__module__', 'Unknown')
}
try:
info['signature'] = str(inspect.signature(func))
except (ValueError, TypeError):
info['signature'] = "Signature not available"
return info
sqrt_info = get_function_info(math, 'sqrt')
print(f"sqrt function info: {sqrt_info}")
# 11. CHECKING PACKAGE CONTENTS
print("\n11. CHECKING PACKAGE CONTENTS:")
print("-" * 30)
def explore_package(package_name):
"""Explore the contents of a package."""
try:
package = importlib.import_module(package_name)
print(f"Package: {package_name}")
print(f" Location: {getattr(package, '__file__', 'Built-in')}")
print(f" Is package: {hasattr(package, '__path__')}")
if hasattr(package, '__path__'):
print(f" Package path: {package.__path__}")
# List submodules
import pkgutil
submodules = []
for importer, modname, ispkg in pkgutil.iter_modules(package.__path__):
submodules.append(modname)
print(f" Submodules: {submodules[:5]}...")
# Check for __all__
if hasattr(package, '__all__'):
print(f" __all__: {package.__all__}")
return package
except ImportError as e:
print(f"Could not import {package_name}: {e}")
return None
# Explore the os package
os_package = explore_package('os')
# 12. MEMORY AND PERFORMANCE INFO
print("\n12. MEMORY AND PERFORMANCE INFO:")
print("-" * 30)
def get_module_size_info(module):
"""Get size information about a module."""
import sys
# Get the module object size
module_size = sys.getsizeof(module)
# Count different types of attributes
attrs = dir(module)
total_attrs = len(attrs)
# Calculate total size of all attributes
total_attr_size = sum(sys.getsizeof(getattr(module, attr)) for attr in attrs)
return {
'module_size': module_size,
'total_attributes': total_attrs,
'total_attributes_size': total_attr_size,
'average_attr_size': total_attr_size / total_attrs if total_attrs > 0 else 0
}
math_size_info = get_module_size_info(math)
print(f"Math module size info: {math_size_info}")
print("\n" + "=" * 60)
print("SUMMARY OF KEY ATTRIBUTES AND METHODS")
print("=" * 60)
summary = """
ESSENTIAL ATTRIBUTES:
- __name__: Module name
- __file__: Module file path
- __doc__: Module documentation
- __package__: Package name
- __path__: Package search path (packages only)
- __all__: Public API list
INSPECTION FUNCTIONS:
- dir(module): List all attributes
- vars(module): Module namespace dictionary
- hasattr(module, 'attr'): Check attribute existence
- getattr(module, 'attr'): Get attribute safely
- inspect.getmembers(module): Get all members
- inspect.signature(func): Get function signature
- inspect.getdoc(func): Get documentation
FILTERING FUNCTIONS:
- inspect.isfunction(): Check if function
- inspect.isbuiltin(): Check if built-in
- inspect.isclass(): Check if class
- inspect.ismodule(): Check if module
ADVANCED INSPECTION:
- inspect.getsource(): Get source code
- inspect.getsourcefile(): Get source file
- pkgutil.iter_modules(): Iterate package modules
- importlib.import_module(): Dynamic import
"""
print(summary)
============================================================
MODULE INSPECTION ATTRIBUTES AND METHODS
============================================================
1. BASIC MODULE ATTRIBUTES:
------------------------------
__name__: math
__file__: /Users/teslim/anaconda3/lib/python3.10/lib-dynload/math.cpython-310-darwin.so
__doc__: This module provides access to the mathematical functions
defined by the C standard....
__package__:
__spec__: ModuleSpec(name='math', loader=<_frozen_importlib_external.ExtensionFileLoader object at 0x103159630>, origin='/Users/teslim/anaconda3/lib/python3.10/lib-dynload/math.cpython-310-darwin.so')
__loader__: <_frozen_importlib_external.ExtensionFileLoader object at 0x103159630>
__cached__: Not available
2. CONTENT INSPECTION FUNCTIONS:
------------------------------
dir(math) - First 10 attributes: ['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh']
vars(math) available: <class 'dict'>
hasattr(math, 'sqrt'): True
hasattr(math, 'nonexistent'): False
getattr(math, 'pi', 'Not found'): 3.141592653589793
getattr(math, 'nonexistent', 'Not found'): Not found
3. USING INSPECT MODULE:
------------------------------
Total members in math module: 64
First 5 members: [('__doc__', 'This module provides access to the mathematical functions\ndefined by the C standard.'), ('__file__', '/Users/teslim/anaconda3/lib/python3.10/lib-dynload/math.cpython-310-darwin.so'), ('__loader__', <_frozen_importlib_external.ExtensionFileLoader object at 0x103159630>), ('__name__', 'math'), ('__package__', '')]
Functions in math: 0
Function names: []
Built-in functions: 53
Built-in names: ['acos', 'acosh', 'asin', 'asinh', 'atan']
Constants/variables: ['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'e', 'inf', 'nan', 'pi', 'tau']
4. CHECKING SPECIFIC TYPES:
------------------------------
functions: 0 items
builtin_functions: 53 items
Examples: ['acos', 'acosh', 'asin']
classes: 0 items
modules: 0 items
constants: 11 items
Examples: ['__doc__', '__file__', '__loader__']
other: 0 items
5. FUNCTION/METHOD INSPECTION:
------------------------------
math.pow signature: (x, y, /)
math.sqrt docstring: Return the square root of x.
example_func signature: (a, b=10, *args, **kwargs)
6. PACKAGE-SPECIFIC ATTRIBUTES:
------------------------------
json.__name__: json
json.__file__: /Users/teslim/anaconda3/lib/python3.10/json/__init__.py
json.__path__: ['/Users/teslim/anaconda3/lib/python3.10/json']
Package path: ['/Users/teslim/anaconda3/lib/python3.10/json']
7. DYNAMIC ATTRIBUTE CHECKING:
------------------------------
Inspecting module: math
Type: <class 'module'>
File: /Users/teslim/anaconda3/lib/python3.10/lib-dynload/math.cpython-310-darwin.so
Package:
Total attributes: 64
Public attributes: 58
Private attributes: 6
Callable attributes: 53
Non-callable attributes: 11
8. MODULE RELATIONSHIPS:
------------------------------
Modules in sys.modules (first 10): ['sys', 'builtins', '_frozen_importlib', '_imp', '_thread', '_warnings', '_weakref', '_io', 'marshal', 'posix']
Is math in sys.modules? True
json.encoder hierarchy: ['json', 'json.encoder']
9. ADVANCED INSPECTION TECHNIQUES:
------------------------------
Source code available for tempfile.mktemp: 1062 characters
Source file: /Users/teslim/anaconda3/lib/python3.10/tempfile.py
Is math built-in? False
10. PRACTICAL UTILITY FUNCTIONS:
------------------------------
Functions with 'log' in name: ['log', 'log10', 'log1p', 'log2']
sqrt function info: {'name': 'sqrt', 'type': 'builtin_function_or_method', 'callable': True, 'doc': 'Return the square root of x.', 'module': 'math', 'signature': '(x, /)'}
11. CHECKING PACKAGE CONTENTS:
------------------------------
Package: os
Location: /Users/teslim/anaconda3/lib/python3.10/os.py
Is package: False
__all__: ['altsep', 'curdir', 'pardir', 'sep', 'pathsep', 'linesep', 'defpath', 'name', 'path', 'devnull', 'SEEK_SET', 'SEEK_CUR', 'SEEK_END', 'fsencode', 'fsdecode', 'get_exec_path', 'fdopen', 'extsep', '_exit', 'CLD_CONTINUED', 'CLD_DUMPED', 'CLD_EXITED', 'CLD_KILLED', 'CLD_STOPPED', 'CLD_TRAPPED', 'DirEntry', 'EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 'EX_NOINPUT', 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 'EX_PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE', 'F_LOCK', 'F_OK', 'F_TEST', 'F_TLOCK', 'F_ULOCK', 'NGROUPS_MAX', 'O_ACCMODE', 'O_APPEND', 'O_ASYNC', 'O_CLOEXEC', 'O_CREAT', 'O_DIRECTORY', 'O_DSYNC', 'O_EVTONLY', 'O_EXCL', 'O_EXLOCK', 'O_FSYNC', 'O_NDELAY', 'O_NOCTTY', 'O_NOFOLLOW', 'O_NOFOLLOW_ANY', 'O_NONBLOCK', 'O_RDONLY', 'O_RDWR', 'O_SHLOCK', 'O_SYMLINK', 'O_SYNC', 'O_TRUNC', 'O_WRONLY', 'POSIX_SPAWN_CLOSE', 'POSIX_SPAWN_DUP2', 'POSIX_SPAWN_OPEN', 'PRIO_PGRP', 'PRIO_PROCESS', 'PRIO_USER', 'P_ALL', 'P_PGID', 'P_PID', 'RTLD_GLOBAL', 'RTLD_LAZY', 'RTLD_LOCAL', 'RTLD_NODELETE', 'RTLD_NOLOAD', 'RTLD_NOW', 'R_OK', 'SCHED_FIFO', 'SCHED_OTHER', 'SCHED_RR', 'SEEK_DATA', 'SEEK_HOLE', 'ST_NOSUID', 'ST_RDONLY', 'TMP_MAX', 'WCONTINUED', 'WCOREDUMP', 'WEXITED', 'WEXITSTATUS', 'WIFCONTINUED', 'WIFEXITED', 'WIFSIGNALED', 'WIFSTOPPED', 'WNOHANG', 'WNOWAIT', 'WSTOPPED', 'WSTOPSIG', 'WTERMSIG', 'WUNTRACED', 'W_OK', 'X_OK', 'abort', 'access', 'chdir', 'chflags', 'chmod', 'chown', 'chroot', 'close', 'closerange', 'confstr', 'confstr_names', 'cpu_count', 'ctermid', 'device_encoding', 'dup', 'dup2', 'environ', 'error', 'execv', 'execve', 'fchdir', 'fchmod', 'fchown', 'fork', 'forkpty', 'fpathconf', 'fspath', 'fstat', 'fstatvfs', 'fsync', 'ftruncate', 'get_blocking', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getegid', 'geteuid', 'getgid', 'getgrouplist', 'getgroups', 'getloadavg', 'getlogin', 'getpgid', 'getpgrp', 'getpid', 'getppid', 'getpriority', 'getsid', 'getuid', 'initgroups', 'isatty', 'kill', 'killpg', 'lchflags', 'lchmod', 'lchown', 'link', 'listdir', 'lockf', 'lseek', 'lstat', 'major', 'makedev', 'minor', 'mkdir', 'mkfifo', 'mknod', 'nice', 'open', 'openpty', 'pathconf', 'pathconf_names', 'pipe', 'posix_spawn', 'posix_spawnp', 'pread', 'preadv', 'putenv', 'pwrite', 'pwritev', 'read', 'readlink', 'readv', 'register_at_fork', 'remove', 'rename', 'replace', 'rmdir', 'scandir', 'sched_get_priority_max', 'sched_get_priority_min', 'sched_yield', 'sendfile', 'set_blocking', 'set_inheritable', 'setegid', 'seteuid', 'setgid', 'setgroups', 'setpgid', 'setpgrp', 'setpriority', 'setregid', 'setreuid', 'setsid', 'setuid', 'stat', 'stat_result', 'statvfs', 'statvfs_result', 'strerror', 'symlink', 'sync', 'sysconf', 'sysconf_names', 'system', 'tcgetpgrp', 'tcsetpgrp', 'terminal_size', 'times', 'times_result', 'truncate', 'ttyname', 'umask', 'uname', 'uname_result', 'unlink', 'unsetenv', 'urandom', 'utime', 'wait', 'wait3', 'wait4', 'waitpid', 'waitstatus_to_exitcode', 'write', 'writev', 'makedirs', 'removedirs', 'renames', 'walk', 'fwalk', 'execl', 'execle', 'execlp', 'execlpe', 'execvp', 'execvpe', 'getenv', 'supports_bytes_environ', 'environb', 'getenvb', 'P_WAIT', 'P_NOWAIT', 'P_NOWAITO', 'spawnv', 'spawnve', 'spawnvp', 'spawnvpe', 'spawnl', 'spawnle', 'spawnlp', 'spawnlpe', 'popen']
12. MEMORY AND PERFORMANCE INFO:
------------------------------
Math module size info: {'module_size': 72, 'total_attributes': 64, 'total_attributes_size': 4393, 'average_attr_size': 68.640625}
============================================================
SUMMARY OF KEY ATTRIBUTES AND METHODS
============================================================
ESSENTIAL ATTRIBUTES:
- __name__: Module name
- __file__: Module file path
- __doc__: Module documentation
- __package__: Package name
- __path__: Package search path (packages only)
- __all__: Public API list
INSPECTION FUNCTIONS:
- dir(module): List all attributes
- vars(module): Module namespace dictionary
- hasattr(module, 'attr'): Check attribute existence
- getattr(module, 'attr'): Get attribute safely
- inspect.getmembers(module): Get all members
- inspect.signature(func): Get function signature
- inspect.getdoc(func): Get documentation
FILTERING FUNCTIONS:
- inspect.isfunction(): Check if function
- inspect.isbuiltin(): Check if built-in
- inspect.isclass(): Check if class
- inspect.ismodule(): Check if module
ADVANCED INSPECTION:
- inspect.getsource(): Get source code
- inspect.getsourcefile(): Get source file
- pkgutil.iter_modules(): Iterate package modules
- importlib.import_module(): Dynamic import