Call python class from another file

Dear community,

Hope this is an inappropriate question, since it involves pure python. Anyway:

I have a single file main.py with following code

class MyStudent:
    def __init__(self,n,a):
        self.full_name = n
        self.age = a
    def get_age(self):
        return self.age

def CountToTenFunction():
    for i in range(0,10):
        print i

if __name__=="__main__":
    CountToTenFunction()
    x = MyStudent("Jan", 24)
    print x.get_age()

which works fine.

However, when I move

class MyStudent
def CountToTenFunction() 

to another file, which I call CountToTen.py

and in my main.py include this file by

from CountToTen import *

only my function CountToTenFunction() is found, but not my class. This gives the error

Message: name 'MyStudent' is not defined

So as a Python beginner, I did something wrong obviously, but have no idea what. Any suggestions?

Many thanks in advance…

Kind regards,

Filip

You can import variables, functions and classes from modules (that’s your CountToTen.py file).
The fact that function can be imported but class can not is strange.
Try posting both your main.py and CountToTen.py files.

OK now I am confused, since after a Rhinoceros close and restart, it works as expected…

OK, seems that when editing external files that I want to import, the old file is used until I restart Rhinoceros. Seems that the old import keeps hanging in memory and is not re-imported when I update the file to be imported.

So I guess my question is transformed if there is a python equivalent of ResetRhinoscript? Or a way to re-import external files in python when those files are edited without restarting Rhino?

And that seems to be possible using Rhino Python editor using menu “Tools” - “Reset script engine”

You could also try using Python’s reload() function. If you have imported a module, importing it again won’t do anything. Calling reload(), however, will load the module again.

There are a few things to watch out for.

  1. reload is a function and requires parentheses (), while import does not.

  2. If you call reload without first calling import, you’ll throw an exception. When debugging scripts, I use this pattern:

try:
reload( my_module)
except:
import my_module

  1. since reload() loads code every time it’s called, it’s unwise to use in production, or where many files are in use. That said, for debugging scripts, it can be very useful.
1 Like