Function: print_link(file, line)
With the help of Frieder's answer I created print_link
which allows you to easily create a link in your PyCharm console. It uses the built-in inspect module to create default values for file
and line
to point to the line that called it.
import inspect
def print_link(file=None, line=None):
""" Print a link in PyCharm to a line in file.
Defaults to line where this function was called. """
if file is None:
file = inspect.stack()[1].filename
if line is None:
line = inspect.stack()[1].lineno
string = f'File "{file}", line {max(line, 1)}'.replace("\\", "/")
print(string)
return string
# Default to this line and file (randomtesting.py in generallibrary, line 14)
print_link()
# Link relatively to another repository through parent's directory
print_link("../generalvector/generalvector/vector.py", 23)
# Link relatively to README which is in same directory as randomtesting.py
print_link("README.md", 1)
# Link absolutely to any file
print_link("A:/hello.txt", 1)
![print_link](https://cdn.statically.io/img/i.sstatic.net/Flnes.png)
Blue text means that the link is successful.
Function: print_link_to_obj(obj)
Building further on the previous function we can create print_link_to_obj
to easily and dynamically create a link to any object which has it's source code available to inspect
.
def print_link_to_obj(obj):
""" Print a link in PyCharm to a module, function, class, method or property. """
if isinstance(obj, property):
obj = obj.fget
file = inspect.getfile(obj)
line = inspect.getsourcelines(obj)[1]
print_link(file=file, line=line)
# Create a link to definition above
print_link_to_obj(print_link)
# Create a link to entire inspect module
print_link_to_obj(inspect)
# Create a link to a function in inspect
print_link_to_obj(inspect.stack)
# Create a link to a property in a class in inspect
print_link_to_obj(inspect.BoundArguments.args)
![print_link_to_obj](https://cdn.statically.io/img/i.sstatic.net/vCB2p.png)
Install my cross-platform package if you don't want to copy-paste the functions:
pip install generallibrary
from generallibrary import print_link, print_link_to_obj