2

How can I redirect to the line from where the definition or class is called?

I want something like this enter image description here

I find it hard to believe this does not exist. I have gone through this https://github.com/krassowski/jupyterlab-go-to-definition but I want similar to this in reverse.

Any help is appreciated.

Binit Amin
  • 481
  • 2
  • 18
  • Do you have to code in a jupyter notebook? Can you write your code in some other IDE and then run it in a jupyter notebook? The way I've done this is to write my code in PyCharm, then use PyCharm or a local jupyter server. With PyCharm, Ctrl-B or Cmd-B depending on your OS & settings, will take you to the definition if you're at a usage, and will find the usages if you're at the definition. – hlongmore Feb 05 '23 at 09:27
  • Just use vscode with jupyter notebook integration. It has this built in – innocent Feb 09 '23 at 14:17

2 Answers2

3

You could install the the LSP Integration for JupyterLab Extension. It doesn't have exactly what you showed there, but it does have many useful features, including "go to definition".

Alternatively, you could run your Jupyter notebooks on VSCode which can be setup with those features much more quickly and easily.

LTambak
  • 56
  • 3
2

If you want to get this reference at a runtime, you can use inspect module in your class to get the python context around it. Here is small example:

# main.py

from utils import MyClass

my_class = MyClass()

my_class.get_the_fish()
# utils.py

import inspect

class MyClass:
    def __init__(self):
        frame = inspect.stack()[1]  # one frame up the stack
        print(f"class initialized from {frame.filename}:{frame.lineno}")
        print(f"code: {frame.code_context}")

    def get_the_fish(self):
        print("got the fish!")
$ python main.py
class initialized from /Users/alice/codebase/main.py:3
code: ['my_class = MyClass()\n']
got the fish!