Skip to content
Advertisement

Jupyter – Split Classes in multiple Cells

I wonder if there is a possibility to split jupyter classes into different cells? Lets say:


#first cell:
class foo(object):
    def __init__(self, var):
        self.var = var

#second cell
    def print_var(self):
       print(self.var)

For more complex classes its really annoying to write them into one cell. I would like to put each method in a different cell.

Someone made this this last year but i wonder if there is something build in so i dont need external scripts/imports.

And if not, i would like to know if there is a reason to not give the opportunity to split your code and document / debug it way easier.

Thanks in advance

Advertisement

Answer

Two solutions were provided to this problem on Github issue “Define a Python class across multiple cells #1243” which can be found here: https://github.com/jupyter/notebook/issues/1243

One solution is using a magic function from a package developed for this specific case called jdc – or Jupyter dynamic classes. The documentation on how to install it and how to use can be found on package url at https://alexhagen.github.io/jdc/

The second solution was provided by Doug Blank and which just work in regular Python, without resorting to any extra magic as follows:

Cell 1:

class MyClass():
    def method1(self):
        print("method1")

Cell 2:

class MyClass(MyClass):
    def method2(self):
        print("method2")

Cell 3:

instance = MyClass()
instance.method1()
instance.method2()

I tested the second solution myself in both Jupyter Notebook and VS Code, and it worked fine in both environments, except that I got a pylint error [pylint] E0102:class already defined line 5 in VS Code, which is kind of expected but still runs fine. Moreover, VS Code was not meant to be the target environment anyway.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement