from typing import Any
from typing import Optional
import functools
import inspect


def get_python_source(x: Any) -> Optional[str]:
    """Helper function to get Python source (or not), preventing exceptions"""
    if isinstance(x, str):
        return x

    if x is None:
        return None

    source_code = None

    if isinstance(x, functools.partial):
        source_code = inspect.getsource(x.func)

    if source_code is None:
        try:
            source_code = inspect.getsource(x)
        except TypeError:
            pass

    if source_code is None:
        try:
            source_code = inspect.getsource(x.__call__)
        except (TypeError, AttributeError):
            pass

    if source_code is None:
        source_code = f'No source code available for {type(x)}'
    return source_code