0

/ How to Convert a string with name of function into a function? Here's my actual example right now. I'm trying to understand graph edges. So when I get an edge from a graph (called 'e'). I'm trying to iterate through all of the methods using dir(e) to understand what the methods do by looking at the outputs. Sometimes I want to do this when I feel lost in documentation.

Another way to put this is, if I had a string that was a function’s name, how could I convert that into the function itself to be called.

I want something that looks like this:

# e is a graph edge
fxns = [f for f in dir(e) if ('get' in f) and ('set' not in f)]
for f in fxns:
    try: print(e.f())
    except: pass

Here's the truncated list of what fxns looks like:

['get_URL',
 'get_arrowhead',
 'get_arrowsize',
 'get_arrowtail',
 'get_attributes',
 'get_color',
 'get_colorscheme',
 'get_comment',
 'get_constraint',
 'get_decorate',
 'get_destination',
 'get_dir',
 'get_edgeURL',
 'get_edgehref',
 'get_edgetarget',
 ...]

And I want the equivalent outcome to be:

print(e.get_URL())
print(e.get_arrowhead())
print(e.get_arrowsize())
...

So I want to go through all of the methods to see what the outputs look like. What I'm actually trying to solve is is figuring out what edge attribute to set as 'True'/'False' for a decision tree viz, but I would actually iterate through methods in a lot of circumstances. This would be super useful if I could figure out how to do it.

ambose
  • 87
  • 3

1 Answers1

0

Credits to these posts for helping me figure this one out. I used eval to make it work. https://docs.python.org/2/library/functions.html#eval

In Python: How do I convert a user input into a piece of code?

How can I get the name of an object in Python?

Here's a 95% working version of what I was looking for:

## This first part is PURELY bc I wanted color. 
from IPython.display import Markdown, display
def printmd(string, color=None):
    if '__' in string:
        colorstr = "__<span style='color:{}'>&#95;{}</span>__".format(color, string)
    else: 
        colorstr = "__<span style='color:{}'>{}</span>__".format(color, string)
    display(Markdown(colorstr))
    
printmd("*italics*, **bold**", color='blue')


# The actual solution. If you don't want formatting/don't want to deal with the above code, replace 'printmd' with print.
 
def describe(model):
    
    # get name of model
    model_name = [objname for objname, oid in globals().items() if id(oid)==id(model)][0]
    
    # create list, sort, but __doc__ at front
    calls = sorted([model_name+ '.' + i for i in dir(PCA)])
    doc_index = calls.index(model_name+'.__doc__')
    calls.pop(doc_index)
    calls = [model_name+'.__doc__'] + calls
    
    # print 
    for c in calls:
        try: 
            if '__' in c:
                printmd(f'{c}',color='blue')
            else:
                printmd(c,color='blue')
                
            printmd(str(eval(c+'()')))
        except Exception as e:
            if 'is not callable' in str(e).lower():
                try:
                    printmd(str(eval(c)))
                except Exception as e:
                    print(e)
            else:
                print(e)
        printmd('/'*20, color='gray')

Output looks like this (but with color in my notebook):


    _PCA.doc____
    
    __Principal component analysis (PCA).
    
    Linear dimensionality reduction using Singular Value Decomposition of the
    data to project it to a lower dimensional space. The input data is centered
    but not scaled for each feature before applying the SVD.
    
    It uses the LAPACK implementation of the full SVD or a randomized truncated
    SVD by the method of Halko et al. 2009, depending on the shape of the input
    data and the number of components to extract.
    
    It can also use the scipy.sparse.linalg ARPACK implementation of the
    truncated SVD.
    
    Notice that this class does not support sparse input. See
    :class:`TruncatedSVD` for an alternative with sparse data.
    
    Read more in the :ref:`User Guide `.
    
    Parameters
    ----------
    n_components : int, float, None or str
        Number of components to keep.
        if n_components is not set all components are kept::
    
            n_components == min(n_samples, n_features)
    
        If ``n_components == 'mle'`` and ``svd_solver == 'full'``, Minka's
        MLE is used to guess the dimension. Use of ``n_components == 'mle'``
        will interpret ``svd_solver == 'auto'`` as ``svd_solver == 'full'``.
    
        If ``0 = 0, optional (default .0)
        Tolerance for singular values computed by svd_solver == 'arpack'.
    
        .. versionadded:: 0.18.0
    
    iterated_power : int >= 0, or 'auto', (default 'auto')
        Number of iterations for the power method computed by
        svd_solver == 'randomized'.
    
        .. versionadded:: 0.18.0
    
    random_state : int, RandomState instance, default=None
        Used when ``svd_solver`` == 'arpack' or 'randomized'. Pass an int
        for reproducible results across multiple function calls.
        See :term:`Glossary `.
    
        .. versionadded:: 0.18.0
    
    Attributes
    ----------
    components_ : array, shape (n_components, n_features)
        Principal axes in feature space, representing the directions of
        maximum variance in the data. The components are sorted by
        ``explained_variance_``.
    
    explained_variance_ : array, shape (n_components,)
        The amount of variance explained by each of the selected components.
    
        Equal to n_components largest eigenvalues
        of the covariance matrix of X.
    
        .. versionadded:: 0.18
    
    explained_variance_ratio_ : array, shape (n_components,)
        Percentage of variance explained by each of the selected components.
    
        If ``n_components`` is not set then all components are stored and the
        sum of the ratios is equal to 1.0.
    
    singular_values_ : array, shape (n_components,)
        The singular values corresponding to each of the selected components.
        The singular values are equal to the 2-norms of the ``n_components``
        variables in the lower-dimensional space.
    
        .. versionadded:: 0.19
    
    mean_ : array, shape (n_features,)
        Per-feature empirical mean, estimated from the training set.
    
        Equal to `X.mean(axis=0)`.
    
    n_components_ : int
        The estimated number of components. When n_components is set
        to 'mle' or a number between 0 and 1 (with svd_solver == 'full') this
        number is estimated from input data. Otherwise it equals the parameter
        n_components, or the lesser value of n_features and n_samples
        if n_components is None.
    
    n_features_ : int
        Number of features in the training data.
    
    n_samples_ : int
        Number of samples in the training data.
    
    noise_variance_ : float
        The estimated noise covariance following the Probabilistic PCA model
        from Tipping and Bishop 1999. See "Pattern Recognition and
        Machine Learning" by C. Bishop, 12.2.1 p. 574 or
        http://www.miketipping.com/papers/met-mppca.pdf. It is required to
        compute the estimated data covariance and score samples.
    
        Equal to the average of (min(n_features, n_samples) - n_components)
        smallest eigenvalues of the covariance matrix of X.
    
    See Also
    --------
    KernelPCA : Kernel Principal Component Analysis.
    SparsePCA : Sparse Principal Component Analysis.
    TruncatedSVD : Dimensionality reduction using truncated SVD.
    IncrementalPCA : Incremental Principal Component Analysis.
    
    References
    ----------
    For n_components == 'mle', this class uses the method of *Minka, T. P.
    "Automatic choice of dimensionality for PCA". In NIPS, pp. 598-604*
    
    Implements the probabilistic PCA model from:
    Tipping, M. E., and Bishop, C. M. (1999). "Probabilistic principal
    component analysis". Journal of the Royal Statistical Society:
    Series B (Statistical Methodology), 61(3), 611-622.
    via the score and score_samples methods.
    See http://www.miketipping.com/papers/met-mppca.pdf
    
    For svd_solver == 'arpack', refer to `scipy.sparse.linalg.svds`.
    
    For svd_solver == 'randomized', see:
    *Halko, N., Martinsson, P. G., and Tropp, J. A. (2011).
    "Finding structure with randomness: Probabilistic algorithms for
    constructing approximate matrix decompositions".
    SIAM review, 53(2), 217-288.* and also
    *Martinsson, P. G., Rokhlin, V., and Tygert, M. (2011).
    "A randomized algorithm for the decomposition of matrices".
    Applied and Computational Harmonic Analysis, 30(1), 47-68.*
    
    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.decomposition import PCA
    >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
    >>> pca = PCA(n_components=2)
    >>> pca.fit(X)
    PCA(n_components=2)
    >>> print(pca.explained_variance_ratio_)
    [0.9924... 0.0075...]
    >>> print(pca.singular_values_)
    [6.30061... 0.54980...]
    
    >>> pca = PCA(n_components=2, svd_solver='full')
    >>> pca.fit(X)
    PCA(n_components=2, svd_solver='full')
    >>> print(pca.explained_variance_ratio_)
    [0.9924... 0.00755...]
    >>> print(pca.singular_values_)
    [6.30061... 0.54980...]
    
    >>> pca = PCA(n_components=1, svd_solver='arpack')
    >>> pca.fit(X)
    PCA(n_components=1, svd_solver='arpack')
    >>> print(pca.explained_variance_ratio_)
    [0.99244...]
    >>> print(pca.singular_values_)
    [6.30061...]
    __
    ////////////////////
    
    _PCA.abstractmethods____
    
    frozenset()
    
    ////////////////////
    
    _PCA.class____
    
    PCA()
    
    ////////////////////
    
    _PCA.delattr____
    
    expected 1 arguments, got 0
    ////////////////////
    
    _PCA.dict____
    
    {'n_components': None, 'copy': True, 'whiten': False, 'svd_solver': 'auto', 'tol': 0.0, 'iterated_power': 'auto', 'random_state': None, 'n_features_in_': 7, '_fit_svd_solver': 'full', 'mean_': array([ 8.51677937e-17, 2.07596497e-16, -6.15945651e-17, -5.47507245e-17, 2.12919484e-16, 3.28767123e-01, 6.71232877e-01]), 'noise_variance_': 0.4511471014202474, 'n_samples_': 73, 'n_features_': 7, 'components_': array([[-0.45434621, -0.35524292, 0.49366373, -0.41320409, 0.47423634, 0.11838578, -0.11838578], [ 0.54661908, -0.36755507, 0.45744847, -0.27707168, -0.51389186, 0.08943766, -0.08943766]]), 'n_components_': 2, 'explained_variance_': array([2.11557313, 1.1456244 ]), 'explained_variance_ratio_': array([0.38346906, 0.20765603]), 'singular_values_': array([12.34185015, 9.0821229 ])}
    
    ////////////////////
    
    _PCA.dir____
    
    _['n_components', 'copy', 'whiten', 'svd_solver', 'tol', 'iterated_power', 'random_state', 'n_features_in_', '_fit_svd_solver', 'mean_', 'noise_variance_', 'n_samples_', 'n_features_', 'components_', 'n_components_', 'explained_variance_', 'explained_variance_ratio_', 'singular_values_', 'module__', 'doc', 'init', 'fit', 'fit_transform', 'fit', 'fit_full', '_fit_truncated', 'score_samples', 'score', 'abstractmethods', '_abc_impl', 'get_covariance', 'get_precision', 'transform', 'inverse_transform', 'dict', 'weakref', 'repr', 'hash', 'str', 'getattribute', 'setattr', 'delattr', 'lt', 'le', 'eq', 'ne', 'gt', 'ge', 'new', 'reduce_ex', 'reduce', 'subclasshook', 'init_subclass', 'format', 'sizeof', 'dir', 'class', '_get_param_names', 'get_params', 'set_params', 'getstate', 'setstate', '_more_tags', '_get_tags', '_check_n_features', '_validate_data', '_repr_html_', '_repr_html_inner', '_repr_mimebundle_']
    
    ////////////////////
    
    _PCA.eq____
    
    expected 1 arguments, got 0
    ////////////////////
    
    _PCA.format____
    
    __format__() takes exactly one argument (0 given)
    ////////////////////
    
    _PCA.ge____
    
    expected 1 arguments, got 0
    ////////////////////
    
    _PCA.getattribute____
    
    expected 1 arguments, got 0
    ////////////////////
    
    _PCA.getstate____
    
    {'n_components': None, 'copy': True, 'whiten': False, 'svd_solver': 'auto', 'tol': 0.0, 'iterated_power': 'auto', 'random_state': None, 'n_features_in_': 7, '_fit_svd_solver': 'full', 'mean_': array([ 8.51677937e-17, 2.07596497e-16, -6.15945651e-17, -5.47507245e-17, 2.12919484e-16, 3.28767123e-01, 6.71232877e-01]), 'noise_variance_': 0.4511471014202474, 'n_samples_': 73, 'n_features_': 7, 'components_': array([[-0.45434621, -0.35524292, 0.49366373, -0.41320409, 0.47423634, 0.11838578, -0.11838578], [ 0.54661908, -0.36755507, 0.45744847, -0.27707168, -0.51389186, 0.08943766, -0.08943766]]), 'n_components_': 2, 'explained_variance_': array([2.11557313, 1.1456244 ]), 'explained_variance_ratio_': array([0.38346906, 0.20765603]), 'singular_values_': array([12.34185015, 9.0821229 ]), '_sklearn_version': '0.23.1'}
    
    ////////////////////
    
    _PCA.gt____
    
    expected 1 arguments, got 0
    ////////////////////
    
    _PCA.hash____
    
    8773832952721
    
    ////////////////////
    
    _PCA.init____
    
    None
    
    ////////////////////
    
    _PCA.init_subclass____
    
    None
    
    ////////////////////
    
    _PCA.le____
    
    expected 1 arguments, got 0
    ////////////////////
    
    _PCA.lt____
    
    expected 1 arguments, got 0
    ////////////////////
    
    _PCA.module____
    
    sklearn.decomposition._pca
    
    ////////////////////
    
    _PCA.ne____
    
    expected 1 arguments, got 0
    ////////////////////
    
    _PCA.new____
    
    object.__new__(): not enough arguments
    ////////////////////
    
    _PCA.reduce____
    
    (, (, , None), {'n_components': None, 'copy': True, 'whiten': False, 'svd_solver': 'auto', 'tol': 0.0, 'iterated_power': 'auto', 'random_state': None, 'n_features_in_': 7, '_fit_svd_solver': 'full', 'mean_': array([ 8.51677937e-17, 2.07596497e-16, -6.15945651e-17, -5.47507245e-17, 2.12919484e-16, 3.28767123e-01, 6.71232877e-01]), 'noise_variance_': 0.4511471014202474, 'n_samples_': 73, 'n_features_': 7, 'components_': array([[-0.45434621, -0.35524292, 0.49366373, -0.41320409, 0.47423634, 0.11838578, -0.11838578], [ 0.54661908, -0.36755507, 0.45744847, -0.27707168, -0.51389186, 0.08943766, -0.08943766]]), 'n_components_': 2, 'explained_variance_': array([2.11557313, 1.1456244 ]), 'explained_variance_ratio_': array([0.38346906, 0.20765603]), 'singular_values_': array([12.34185015, 9.0821229 ]), '_sklearn_version': '0.23.1'})
    
    ////////////////////
    
    _PCA.reduce_ex____
    
    __reduce_ex__() takes exactly one argument (0 given)
    ////////////////////
    
    _PCA.repr____
    
    PCA()
    
    ////////////////////
    
    _PCA.setattr____
    
     expected 2 arguments, got 0
    ////////////////////
    
    _PCA.setstate____
    
    __setstate__() missing 1 required positional argument: 'state'
    ////////////////////
    
    _PCA.sizeof____
    
    32
    
    ////////////////////
    
    _PCA.str____
    
    PCA()
    
    ////////////////////
    
    _PCA.subclasshook____
    
    NotImplemented
    
    ////////////////////
    
    _PCA.weakref____
    
    None
    
    ////////////////////
    
    PCA._abc_impl
    
    
    
    ////////////////////
    
    PCA._check_n_features
    
    _check_n_features() missing 2 required positional arguments: 'X' and 'reset'
    ////////////////////
    
    PCA._fit
    
    _fit() missing 1 required positional argument: 'X'
    ////////////////////
    
    PCA._fit_full
    
    _fit_full() missing 2 required positional arguments: 'X' and 'n_components'
    ////////////////////
    
    PCA._fit_svd_solver
    
    full
    
    ////////////////////
    
    PCA._fit_truncated
    
    _fit_truncated() missing 3 required positional arguments: 'X', 'n_components', and 'svd_solver'
    ////////////////////
    
    PCA._get_param_names
    
    ['copy', 'iterated_power', 'n_components', 'random_state', 'svd_solver', 'tol', 'whiten']
    
    ////////////////////
    
    PCA._get_tags
    
    {'non_deterministic': False, 'requires_positive_X': False, 'requires_positive_y': False, 'X_types': ['2darray'], 'poor_score': False, 'no_validation': False, 'multioutput': False, 'allow_nan': False, 'stateless': False, 'multilabel': False, '_skip_test': False, '_xfail_checks': False, 'multioutput_only': False, 'binary_only': False, 'requires_fit': True, 'requires_y': False}
    
    ////////////////////
    
    PCA._more_tags
    
    {'non_deterministic': False, 'requires_positive_X': False, 'requires_positive_y': False, 'X_types': ['2darray'], 'poor_score': False, 'no_validation': False, 'multioutput': False, 'allow_nan': False, 'stateless': False, 'multilabel': False, '_skip_test': False, '_xfail_checks': False, 'multioutput_only': False, 'binary_only': False, 'requires_fit': True, 'requires_y': False}
    
    ////////////////////
    
    PCA._repr_html_
    
    _repr_html_ is only defined when the 'display' configuration option is set to 'diagram'
    ////////////////////
    
    PCA._repr_html_inner
    
    _
    
    PCA
    __
    ////////////////////
    
    PCA._repr_mimebundle_
    
    {'text/plain': 'PCA()'}
    
    ////////////////////
    
    PCA._validate_data
    
    _validate_data() missing 1 required positional argument: 'X'
    ////////////////////
    
    PCA.components_
    
    [[-0.45434621 -0.35524292 0.49366373 -0.41320409 0.47423634 0.11838578 -0.11838578] [ 0.54661908 -0.36755507 0.45744847 -0.27707168 -0.51389186 0.08943766 -0.08943766]]
    
    ////////////////////
    
    PCA.copy
    
    True
    
    ////////////////////
    
    PCA.explained_variance_
    
    [2.11557313 1.1456244 ]
    
    ////////////////////
    
    PCA.explained_variance_ratio_
    
    [0.38346906 0.20765603]
    
    ////////////////////
    
    PCA.fit
    
    fit() missing 1 required positional argument: 'X'
    ////////////////////
    
    PCA.fit_transform
    
    fit_transform() missing 1 required positional argument: 'X'
    ////////////////////
    
    PCA.get_covariance
    
    [[ 1.00223991 0.12911456 -0.19966709 0.20729509 -0.55371051 -0.05557453 0.05557453] [ 0.12911456 0.75501517 -0.40865898 0.31504242 -0.14922901 -0.09282835 0.09282835] [-0.19966709 -0.40865898 1.00209988 -0.4275383 0.22640718 0.12568689 -0.12568689] [ 0.20729509 0.31504242 -0.4275383 0.78864137 -0.22727185 -0.09862913 0.09862913] [-0.55371051 -0.14922901 0.22640718 -0.22727185 1.00887762 0.06152653 -0.06152653] [-0.05557453 -0.09282835 0.12568689 -0.09862913 0.06152653 0.48002954 -0.02888244] [ 0.05557453 0.09282835 -0.12568689 0.09862913 -0.06152653 -0.02888244 0.48002954]]
    
    ////////////////////
    
    PCA.get_params
    
    {'copy': True, 'iterated_power': 'auto', 'n_components': None, 'random_state': None, 'svd_solver': 'auto', 'tol': 0.0, 'whiten': False}
    
    ////////////////////
    
    PCA.get_precision
    
    [[ 1.45509751 -0.01150567 0.05515513 -0.12388856 0.75319631 0.02810987 -0.02810987] [-0.01150567 1.8149702 0.5317503 -0.39282107 0.03999094 0.11751172 -0.11751172] [ 0.05515513 0.5317503 1.51040153 0.52603156 -0.09239476 -0.15689193 0.15689193] [-0.12388856 -0.39282107 0.52603156 1.81567184 0.15040527 0.11860395 -0.11860395] [ 0.75319631 0.03999094 -0.09239476 0.15040527 1.46952464 -0.03614924 0.03614924] [ 0.02810987 0.11751172 -0.15689193 0.11860395 -0.03614924 2.18138275 0.03518918] [-0.02810987 -0.11751172 0.15689193 -0.11860395 0.03614924 0.03518918 2.18138275]]
    
    ////////////////////
    
    PCA.inverse_transform
    
    inverse_transform() missing 1 required positional argument: 'X'
    ////////////////////
    
    PCA.iterated_power
    
    auto
    
    ////////////////////
    
    PCA.mean_
    
    [ 8.51677937e-17 2.07596497e-16 -6.15945651e-17 -5.47507245e-17 2.12919484e-16 3.28767123e-01 6.71232877e-01]
    
    ////////////////////
    
    PCA.n_components
    
    None
    
    ////////////////////
    
    PCA.n_components_
    
    2
    
    ////////////////////
    
    PCA.n_features_
    
    7
    
    ////////////////////
    
    PCA.n_features_in_
    
    7
    
    ////////////////////
    
    PCA.n_samples_
    
    73
    
    ////////////////////
    
    PCA.noise_variance_
    
    0.4511471014202474
    
    ////////////////////
    
    PCA.random_state
    
    None
    
    ////////////////////
    
    PCA.score
    
    score() missing 1 required positional argument: 'X'
    ////////////////////
    
    PCA.score_samples
    
    score_samples() missing 1 required positional argument: 'X'
    ////////////////////
    
    PCA.set_params
    
    PCA()
    
    ////////////////////
    
    PCA.singular_values_
    
    [12.34185015 9.0821229 ]
    
    ////////////////////
    
    PCA.svd_solver
    
    auto
    
    ////////////////////
    
    PCA.tol
    
    0.0
    
    ////////////////////
    
    PCA.transform
    
    transform() missing 1 required positional argument: 'X'
    ////////////////////
    
    PCA.whiten
    
    False
    
    ////////////////////

ambose
  • 87
  • 3