Source code for nnsa.utils.objects

"""
General functions for Python objects.
"""
from nnsa.utils.dictionaries import itemize_items
from nnsa.utils.testing import assert_equal

__all__ = [
    'basic_repr',
    'convert_to_nnsa_class_callable',
    'list_attrs',
    'list_methods',
    'print_object_summary',
]


[docs]def basic_repr(obj): """ Return string with basic information about object. Useful as a default for __repr__ method. Args: obj (object): the object to print. Returns: (str): string with info about object (class name and attributes). """ attributes = itemize_items(obj.__dict__.items()) return '{} with attributes:\n{}'.format(obj.__class__.__name__, attributes)
[docs]def convert_to_nnsa_class_callable(class_name): """ Convert a string ontaining the name of a class to a callable object. Args: class_name (str): string of a class name defined in the nnsa package. Returns: class_def (type): class definition corresponding to input class_name. Examples: >>> from nnsa import ResultBase >>> a = convert_to_nnsa_class_callable('ResultBase')(None) >>> b = ResultBase(None) # Equivalent to the above statement. >>> assert_equal(a, b) """ # Get class callable. import nnsa class_def = eval('nnsa.{}'.format(class_name)) return class_def
[docs]def list_attrs(obj): """ Returns a list with names of public attributes of an object. Args: obj (object): the object of which to get the attributes of. Returns: (list of str): list with strings containing the attribute names of the object. """ # Ignore all attributes that start with underscore (those are not public by convention). return [a for a in dir(obj) if not callable(getattr(obj, a)) if not a.startswith('_')]
[docs]def list_methods(obj): """ Returns a list with names of public (callable) methods of an object. Args: obj (object): the object of which to get the methods of. Returns: (list of str): list with strings containing the method names of the object. """ # Ignore all methods that start with underscore (those are not public by convention). return [m for m in dir(obj) if callable(getattr(obj, m)) and not m.startswith('_')]