Reputation: 41
I'm an artist that is new to python/coding in general, and also have trouble reading this doc. https://docs.python.org/2/library/inspect.html#
I am trying to understand how to use the inspect
module.
This file is called TestClassA.py:
import inspect
class TestClassA(object):
def __init__(self):
print "this is crazy!"
print inspect.isclass(TestClassA)
#result is True
What I'm trying to do is to return TestClassA
and everything in it. The basic concept is to copy my code and have it pop out as a message
print inspect.getsource(TestClassA)
Result is:
TypeError: <module '__main__' (built-in)> is a built-in class
But this is Funny. if i use:
print inspect.isclass(TestClassA)
the result is True.
So my ultimate goal is to copy a specific type of classes into text (reminder: multiple of classes can be under one .py file) and bring that specific type of class in to another .py file.
Can anyone help me out? I would highly appreciate if anyone can also set an example on how inspect.getsourcefile
and inspect.getsourcelines
work using the same simple example above.
Upvotes: 3
Views: 4449
Reputation: 27
import inspect
class TestClassA:
def __init__(self):
print "Hello"
print inspect.getsource(TestClassA)
Workig for me in pycharm, If you try to use it in interactive mode,run this
import os
import inspect
inspect.getsource(os)
Two methods you mentioned does the same thing only return types are different Check https://docs.python.org/2/library/inspect.html#inspect.getsourcelines
Upvotes: 2