Nicely print "public" methods of python class - python

I am trying to design an API in python using a class:
class SimulationApi(object):
def hello(self):
return "Hi"
def echo(self, string):
return string
def get_foo(self):
return self.foo
def __init__(self):
self.foo = 50
And i'd like to print to console a list of available public methods defined by the class. Is there a way to to this automatically, that will also pick up the method parameters? Ideally, the output would look like this:
SimulationApi:
get_foo()
echo(string)
hello()
So far, my solution is this, but it is not complete and may be the wrong direction.
print("SimulationApi: \n\t{}\n".format("\n\t".join([x+"()" for x in dir(SimulationApi) if not x.startswith("__")]))

You can use inspect module:
class SimulationApi(object):
def hello(self):
return "Hi"
def echo(self, string):
return string
def get_foo(self):
return self.foo
def __init__(self):
self.foo = 50
import inspect
inspect.getmembers(SimulationApi)
Will return:
[('__class__', type),
('__delattr__', <slot wrapper '__delattr__' of 'object' objects>),
('__dict__',
mappingproxy({'__module__': '__main__',
'hello': <function __main__.SimulationApi.hello(self)>,
'echo': <function __main__.SimulationApi.echo(self, string)>,
'get_foo': <function __main__.SimulationApi.get_foo(self)>,
'__init__': <function __main__.SimulationApi.__init__(self)>,
'__dict__': <attribute '__dict__' of 'SimulationApi' objects>,
'__weakref__': <attribute '__weakref__' of 'SimulationApi' objects>,
'__doc__': None})),
('__dir__', <method '__dir__' of 'object' objects>),
('__doc__', None),
('__eq__', <slot wrapper '__eq__' of 'object' objects>),
('__format__', <method '__format__' of 'object' objects>),
('__ge__', <slot wrapper '__ge__' of 'object' objects>),
('__getattribute__', <slot wrapper '__getattribute__' of 'object' objects>),
('__gt__', <slot wrapper '__gt__' of 'object' objects>),
('__hash__', <slot wrapper '__hash__' of 'object' objects>),
('__init__', <function __main__.SimulationApi.__init__(self)>),
('__init_subclass__', <function SimulationApi.__init_subclass__>),
('__le__', <slot wrapper '__le__' of 'object' objects>),
('__lt__', <slot wrapper '__lt__' of 'object' objects>),
('__module__', '__main__'),
('__ne__', <slot wrapper '__ne__' of 'object' objects>),
('__new__', <function object.__new__(*args, **kwargs)>),
('__reduce__', <method '__reduce__' of 'object' objects>),
('__reduce_ex__', <method '__reduce_ex__' of 'object' objects>),
('__repr__', <slot wrapper '__repr__' of 'object' objects>),
('__setattr__', <slot wrapper '__setattr__' of 'object' objects>),
('__sizeof__', <method '__sizeof__' of 'object' objects>),
('__str__', <slot wrapper '__str__' of 'object' objects>),
('__subclasshook__', <function SimulationApi.__subclasshook__>),
('__weakref__', <attribute '__weakref__' of 'SimulationApi' objects>),
('echo', <function __main__.SimulationApi.echo(self, string)>),
('get_foo', <function __main__.SimulationApi.get_foo(self)>),
('hello', <function __main__.SimulationApi.hello(self)>)]
Note: Your methods (the methods you like to get info) are also the SimulationApi class dictionary __dict__.
You can get the full code for your echo function like this:
import inspect
lines = inspect.getsource(SimulationApi.echo)
print(lines)
def echo(self, string):
return string

Related

Equivalent implementation using f-strings and eval

x = type.__dict__
x is x
gives,
True
but,
x = type.__dict__
operator = 'is'
eval(f'{x} {operator} {x}')
gives,
SyntaxError: invalid syntax
even,
operator = 'is'
eval(f'{x!r} {operator} {x!r}')
gives,
SyntaxError: invalid syntax
how to get True as output using eval and f-strings?
When using eval you are executing exactly what you wrote in the string. By formatting with the curly brakets you are inserting in the string the value of "x", or at least whatever is returned by the "__str__" method of x.
print(f"{x}")
gives
{'__repr__': <slot wrapper '__repr__' of 'type' objects>, '__call__': <slot wrapper '__call__' of 'type' objects>, '__getattribute__': <slot wrapper '__getattribute__' of 'type' objects>, '__setattr__': <slot wrapper '__setattr__' of 'type' objects>, '__delattr__': <slot wrapper '__delattr__' of 'type' objects>, '__init__': <slot wrapper '__init__' of 'type' objects>, '__new__': <built-in method __new__ of type object at 0x908780>, 'mro': <method 'mro' of 'type' objects>, '__subclasses__': <method '__subclasses__' of 'type' objects>, '__prepare__': <method '__prepare__' of 'type' objects>, '__instancecheck__': <method '__instancecheck__' of 'type' objects>, '__subclasscheck__': <method '__subclasscheck__' of 'type' objects>, '__dir__': <method '__dir__' of 'type' objects>, '__sizeof__': <method '__sizeof__' of 'type' objects>, '__basicsize__': <member '__basicsize__' of 'type' objects>, '__itemsize__': <member '__itemsize__' of 'type' objects>, '__flags__': <member '__flags__' of 'type' objects>, '__weakrefoffset__': <member '__weakrefoffset__' of 'type' objects>, '__base__': <member '__base__' of 'type' objects>, '__dictoffset__': <member '__dictoffset__' of 'type' objects>, '__mro__': <member '__mro__' of 'type' objects>, '__name__': <attribute '__name__' of 'type' objects>, '__qualname__': <attribute '__qualname__' of 'type' objects>, '__bases__': <attribute '__bases__' of 'type' objects>, '__module__': <attribute '__module__' of 'type' objects>, '__abstractmethods__': <attribute '__abstractmethods__' of 'type' objects>, '__dict__': <attribute '__dict__' of 'type' objects>, '__doc__': <attribute '__doc__' of 'type' objects>, '__text_signature__': <attribute '__text_signature__' of 'type' objects>}
Meaning that's what you are trying to execute, which is indeed invalid syntax.
You should instead do:
eval("x is x")
Works for me:
>>> d = {"a":42}
{'a': 42}
>>> print(f"{d} is {d}")
{'a': 42} is {'a': 42}
>>> {'a': 42} is {'a': 42}
False
>>> eval(f"{d} is {d}")
False
This works just fine with dicts.
However, calling str.__dict__ returns something completely different than you'd probably expect:
>>> str.__dict__
mappingproxy({
'__new__': <built-in method __new__ of type object at 0x00007FFC55D1AC60>,
'__repr__': <slot wrapper '__repr__' of 'str' objects>,
--- snip for readability ---
This "dict-representation" is actually a MappingProxy as you can verify with type(str.__dict__) and cannot exactly be re-interpreted by eval() as <built-in method __new__... is obviously a syntax error, when used without quotes. You can easily verify this by pasting this into a Python interpreter:
>>> {"myKey": <built-in method __new__ of type object at 0x00007FFC55D1AC60>}
File "<stdin>", line 1
{"myKey": <built-in method __new__ of type object at 0x00007FFC55D1AC60>}
^
SyntaxError: invalid syntax
What you're trying to do requires not only type (whatever this might be at runtime) to have a dict-representation, but also every member to have one - recursively! This is hard to assume in a general case.
I'm convinced what you're trying to achieve can be done using a different way - if you want elaborate your task at hand, there might be a more suitable way.
If you insist on the eval() way, take a look at repr() and eval(), as generally, repr tries to produce a string, which can be fed into eval to produce the very same object again.
However, this is possible only, if the object implements repr to do exactly that - which is not guaranteed. There might be objects which cannot be serialized that way.
myDict = {"myKey": "myVal"}
myDict == eval(repr(myDict))
# Output: True
To get the same as x is x through eval you need the name of the variable as a string "x" instead of the variable itself. How to get it is answered here: Getting the name of a variable as a string
Here is a solution for your case:
x = type.__dict__
operator = 'is'
x_name = f'{x=}'.split('=')[0]
eval(f'{x_name} {operator} {x_name}')
Resulting in:
> True

How to chain functions? [duplicate]

This question already has answers here:
Basic method chaining
(3 answers)
Closed 3 years ago.
I am trying to understand the mechanics of chained functions such as
>>> 'hello'.upper()
'HELLO'
(the chain can be longer, I do not have a good example in my head right now - something like 'hello'.upper().reverse().take_every_second_character().rot13())
How is this functionality achieved? What must be returned by each of the functions (and intercepted (= used as a parameter?) by the next one), taken into account that one can break the chain somewhere and still get an output? To take the fictional example above:
>>> 'hello'
'hello'
>>> 'hello'.upper()
'HELLO'
>>> 'hello'.upper().reverse()
'OLLEH'
etc.
'hello' is a str object.
str class has methods (like upper(), reverse(), etc.) that return the string transformed.
You could extend the str class to create your own methods.
>>> import inspect
>>> from pprint import pprint
>>>
>>> str
<class 'str'>
>>> pprint(inspect.getmembers(str))
[('__add__', <slot wrapper '__add__' of 'str' objects>),
('__class__', <class 'type'>),
('__contains__', <slot wrapper '__contains__' of 'str' objects>),
('__delattr__', <slot wrapper '__delattr__' of 'object' objects>),
('__dir__', <method '__dir__' of 'object' objects>),
('__doc__',
"str(object='') -> str\n"
'str(bytes_or_buffer[, encoding[, errors]]) -> str\n'
'\n'
'Create a new string object from the given object. If encoding or\n'
'errors is specified, then the object must expose a data buffer\n'
'that will be decoded using the given encoding and error handler.\n'
'Otherwise, returns the result of object.__str__() (if defined)\n'
'or repr(object).\n'
'encoding defaults to sys.getdefaultencoding().\n'
"errors defaults to 'strict'."),
('__eq__', <slot wrapper '__eq__' of 'str' objects>),
('__format__', <method '__format__' of 'str' objects>),
('__ge__', <slot wrapper '__ge__' of 'str' objects>),
('__getattribute__', <slot wrapper '__getattribute__' of 'str' objects>),
('__getitem__', <slot wrapper '__getitem__' of 'str' objects>),
('__getnewargs__', <method '__getnewargs__' of 'str' objects>),
('__gt__', <slot wrapper '__gt__' of 'str' objects>),
('__hash__', <slot wrapper '__hash__' of 'str' objects>),
('__init__', <slot wrapper '__init__' of 'object' objects>),
('__init_subclass__',
<built-in method __init_subclass__ of type object at 0x7f9d596539c0>),
('__iter__', <slot wrapper '__iter__' of 'str' objects>),
('__le__', <slot wrapper '__le__' of 'str' objects>),
('__len__', <slot wrapper '__len__' of 'str' objects>),
('__lt__', <slot wrapper '__lt__' of 'str' objects>),
('__mod__', <slot wrapper '__mod__' of 'str' objects>),
('__mul__', <slot wrapper '__mul__' of 'str' objects>),
('__ne__', <slot wrapper '__ne__' of 'str' objects>),
('__new__', <built-in method __new__ of type object at 0x7f9d596539c0>),
('__reduce__', <method '__reduce__' of 'object' objects>),
('__reduce_ex__', <method '__reduce_ex__' of 'object' objects>),
('__repr__', <slot wrapper '__repr__' of 'str' objects>),
('__rmod__', <slot wrapper '__rmod__' of 'str' objects>),
('__rmul__', <slot wrapper '__rmul__' of 'str' objects>),
('__setattr__', <slot wrapper '__setattr__' of 'object' objects>),
('__sizeof__', <method '__sizeof__' of 'str' objects>),
('__str__', <slot wrapper '__str__' of 'str' objects>),
('__subclasshook__',
<built-in method __subclasshook__ of type object at 0x7f9d596539c0>),
('capitalize', <method 'capitalize' of 'str' objects>),
('casefold', <method 'casefold' of 'str' objects>),
('center', <method 'center' of 'str' objects>),
('count', <method 'count' of 'str' objects>),
('encode', <method 'encode' of 'str' objects>),
('endswith', <method 'endswith' of 'str' objects>),
('expandtabs', <method 'expandtabs' of 'str' objects>),
('find', <method 'find' of 'str' objects>),
('format', <method 'format' of 'str' objects>),
('format_map', <method 'format_map' of 'str' objects>),
('index', <method 'index' of 'str' objects>),
('isalnum', <method 'isalnum' of 'str' objects>),
('isalpha', <method 'isalpha' of 'str' objects>),
('isascii', <method 'isascii' of 'str' objects>),
('isdecimal', <method 'isdecimal' of 'str' objects>),
('isdigit', <method 'isdigit' of 'str' objects>),
('isidentifier', <method 'isidentifier' of 'str' objects>),
('islower', <method 'islower' of 'str' objects>),
('isnumeric', <method 'isnumeric' of 'str' objects>),
('isprintable', <method 'isprintable' of 'str' objects>),
('isspace', <method 'isspace' of 'str' objects>),
('istitle', <method 'istitle' of 'str' objects>),
('isupper', <method 'isupper' of 'str' objects>),
('join', <method 'join' of 'str' objects>),
('ljust', <method 'ljust' of 'str' objects>),
('lower', <method 'lower' of 'str' objects>),
('lstrip', <method 'lstrip' of 'str' objects>),
('maketrans', <built-in method maketrans of type object at 0x7f9d596539c0>),
('partition', <method 'partition' of 'str' objects>),
('replace', <method 'replace' of 'str' objects>),
('rfind', <method 'rfind' of 'str' objects>),
('rindex', <method 'rindex' of 'str' objects>),
('rjust', <method 'rjust' of 'str' objects>),
('rpartition', <method 'rpartition' of 'str' objects>),
('rsplit', <method 'rsplit' of 'str' objects>),
('rstrip', <method 'rstrip' of 'str' objects>),
('split', <method 'split' of 'str' objects>),
('splitlines', <method 'splitlines' of 'str' objects>),
('startswith', <method 'startswith' of 'str' objects>),
('strip', <method 'strip' of 'str' objects>),
('swapcase', <method 'swapcase' of 'str' objects>),
('title', <method 'title' of 'str' objects>),
('translate', <method 'translate' of 'str' objects>),
('upper', <method 'upper' of 'str' objects>),
('zfill', <method 'zfill' of 'str' objects>)]
Assuming these functions all exist and return the appropriate types.
res = 'hello'
res.upper().reverse().take_every_second_character().rot13()
is equivalent to saying:
res = 'hello'
((((res.upper()).reverse()).take_every_second_character()).rot13())
OR
res = 'hello'.upper()
res = res.reverse()
res = res.take_every_second_character()
res.rot13()
You cannot "break the chain" (if one fails, meaning an error, then an error will be thrown unless you catch it).

How does a object in python find its available methods?

please help me on this topic : If I try to print object.dict, it only shows instance variables and not the methods where as classes do show it's variable and method functions.
If I consider powershell objects, then it does show it's method and properties and many more attributes.
example : powershell_object | get-member
you can use dir(obj) and get the methods and instance variables, then you can filter them to only functions like this:
object_functions = {}
for obj_member in dir(obj):
if callable(getattr(obj, obj_member)):
object_functions[obj_member] = getattr(obj, obj_member)
Methods are functions that belong to the objects's __class__, and to all the classes in it's class method-resolution order, which you can introspect using: __class__.__mro__
So consider:
In [15]: class A(object):
...: def amethod(self): pass
...: class B(A):
...: def bmethod(self): pass
...: class C(A):
...: def cmethod(self): pass
...: class D(B, C):
...: def dmethod(self): pass
...:
In [16]: d = D()
In [17]: vars(D)
Out[17]:
mappingproxy({'__module__': '__main__',
'dmethod': <function __main__.D.dmethod(self)>,
'__doc__': None})
Note, vars just returns __dict__. Notice, D.__dict__ only has dmethod. Now consider:
In [18]: D.__mro__
Out[18]: (__main__.D, __main__.B, __main__.C, __main__.A, object)
In [19]: from pprint import pprint
In [20]: for klass in D.__mro__:
...: print(klass, end=' '); pprint(vars(klass))
...:
<class '__main__.D'> mappingproxy({'__doc__': None,
'__module__': '__main__',
'dmethod': <function D.dmethod at 0x106e72048>})
<class '__main__.B'> mappingproxy({'__doc__': None,
'__module__': '__main__',
'bmethod': <function B.bmethod at 0x106e72ea0>})
<class '__main__.C'> mappingproxy({'__doc__': None,
'__module__': '__main__',
'cmethod': <function C.cmethod at 0x106e72158>})
<class '__main__.A'> mappingproxy({'__dict__': <attribute '__dict__' of 'A' objects>,
'__doc__': None,
'__module__': '__main__',
'__weakref__': <attribute '__weakref__' of 'A' objects>,
'amethod': <function A.amethod at 0x106e72400>})
<class 'object'> mappingproxy({'__class__': <attribute '__class__' of 'object' objects>,
'__delattr__': <slot wrapper '__delattr__' of 'object' objects>,
'__dir__': <method '__dir__' of 'object' objects>,
'__doc__': 'The most base type',
'__eq__': <slot wrapper '__eq__' of 'object' objects>,
'__format__': <method '__format__' of 'object' objects>,
'__ge__': <slot wrapper '__ge__' of 'object' objects>,
'__getattribute__': <slot wrapper '__getattribute__' of 'object' objects>,
'__gt__': <slot wrapper '__gt__' of 'object' objects>,
'__hash__': <slot wrapper '__hash__' of 'object' objects>,
'__init__': <slot wrapper '__init__' of 'object' objects>,
'__init_subclass__': <method '__init_subclass__' of 'object' objects>,
'__le__': <slot wrapper '__le__' of 'object' objects>,
'__lt__': <slot wrapper '__lt__' of 'object' objects>,
'__ne__': <slot wrapper '__ne__' of 'object' objects>,
'__new__': <built-in method __new__ of type object at 0x104ebe518>,
'__reduce__': <method '__reduce__' of 'object' objects>,
'__reduce_ex__': <method '__reduce_ex__' of 'object' objects>,
'__repr__': <slot wrapper '__repr__' of 'object' objects>,
'__setattr__': <slot wrapper '__setattr__' of 'object' objects>,
'__sizeof__': <method '__sizeof__' of 'object' objects>,
'__str__': <slot wrapper '__str__' of 'object' objects>,
'__subclasshook__': <method '__subclasshook__' of 'object' objects>})

Inspecting Python Objects

I am looking at a code given to me by a co-worker who no longer works with us.
I have a list variable called rx.
>> type(rx)
type 'list'
When I go to look inside rx[0] I get this:
>> rx[0]
<Thing.thing.stuff.Rx object at 0x10e1e1c10>
Can anyone translate what this means? And, more importantly, how can I see what is inside this object within the rx list?
Any help is appreciated.
Start with help: help(rx[0])
# example python object
class Employee:
"""Common base class for all employees."""
empCount = 0
help(Employee)
Output:
Help on class Employee in module __main__:
class Employee(builtins.object)
| Common base class for all employees.
|
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| empCount = 0
If that's not enough info check out the inspect module.
Inspect has a lot of methods that might be useful, like getmembers and getdoc:
import inspect
inspect.getdoc(Employee) # 'Common base class for all employees.'
for name, data in inspect.getmembers(Employee):
if name == '__builtins__':
continue
print('%s :' % name, repr(data))
Output:
__class__ : <class 'type'>
__delattr__ : <slot wrapper '__delattr__' of 'object' objects>
__dict__ : mappingproxy({'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Employee' objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>, 'empCount': 0, '__doc__': 'Common base class for all employees.'})
__dir__ : <method '__dir__' of 'object' objects>
__doc__ : 'Common base class for all employees.'
__eq__ : <slot wrapper '__eq__' of 'object' objects>
__format__ : <method '__format__' of 'object' objects>
__ge__ : <slot wrapper '__ge__' of 'object' objects>
__getattribute__ : <slot wrapper '__getattribute__' of 'object' objects>
__gt__ : <slot wrapper '__gt__' of 'object' objects>
__hash__ : <slot wrapper '__hash__' of 'object' objects>
__init__ : <slot wrapper '__init__' of 'object' objects>
__le__ : <slot wrapper '__le__' of 'object' objects>
__lt__ : <slot wrapper '__lt__' of 'object' objects>
__module__ : '__main__'
__ne__ : <slot wrapper '__ne__' of 'object' objects>
__new__ : <built-in method __new__ of type object at 0x108a69d20>
__reduce__ : <method '__reduce__' of 'object' objects>
__reduce_ex__ : <method '__reduce_ex__' of 'object' objects>
__repr__ : <slot wrapper '__repr__' of 'object' objects>
__setattr__ : <slot wrapper '__setattr__' of 'object' objects>
__sizeof__ : <method '__sizeof__' of 'object' objects>
__str__ : <slot wrapper '__str__' of 'object' objects>
__subclasshook__ : <built-in method __subclasshook__ of type object at 0x7faa994086e8>
__weakref__ : <attribute '__weakref__' of 'Employee' objects>
empCount : 0

Finding out which functions are available from a class instance in python?

How do you dynamically find out which functions have been defined from an instance of a class?
For example:
class A(object):
def methodA(self, intA=1):
pass
def methodB(self, strB):
pass
a = A()
Ideally I want to find out that the instance 'a' has methodA and methodB, and which arguments they take?
Have a look at the inspect module.
>>> import inspect
>>> inspect.getmembers(a)
[('__class__', <class '__main__.A'>),
('__delattr__', <method-wrapper '__delattr__' of A object at 0xb77d48ac>),
('__dict__', {}),
('__doc__', None),
('__getattribute__',
<method-wrapper '__getattribute__' of A object at 0xb77d48ac>),
('__hash__', <method-wrapper '__hash__' of A object at 0xb77d48ac>),
('__init__', <method-wrapper '__init__' of A object at 0xb77d48ac>),
('__module__', '__main__'),
('__new__', <built-in method __new__ of type object at 0x8146220>),
('__reduce__', <built-in method __reduce__ of A object at 0xb77d48ac>),
('__reduce_ex__', <built-in method __reduce_ex__ of A object at 0xb77d48ac>),
('__repr__', <method-wrapper '__repr__' of A object at 0xb77d48ac>),
('__setattr__', <method-wrapper '__setattr__' of A object at 0xb77d48ac>),
('__str__', <method-wrapper '__str__' of A object at 0xb77d48ac>),
('__weakref__', None),
('methodA', <bound method A.methodA of <__main__.A object at 0xb77d48ac>>),
('methodB', <bound method A.methodB of <__main__.A object at 0xb77d48ac>>)]
>>> inspect.getargspec(a.methodA)
(['self', 'intA'], None, None, (1,))
>>> inspect.getargspec(getattr(a, 'methodA'))
(['self', 'intA'], None, None, (1,))
>>> print inspect.getargspec.__doc__
Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.
>>> print inspect.getmembers.__doc__
Return all members of an object as (name, value) pairs sorted by name.
Optionally, only return members that satisfy a given predicate.

Categories