1

I defined a class called Prof in a script called AddPntCode90_27.py. It opens some files, does some math, creates output files and so. Now I want to re-use the class for another programme. But as AddPntCode90_27.py is not a module it always executes the script instead of just importing the class. I did from AddPntCode90_27 import * as well as from AddPntCode90_27 import Prof. I am familiar with this article. So my questions are:

  • is it bad practice to define a class within a script like this? Should I always keep them in a separated file?
  • is there, however, a way to import just the class and its methods without executing the script it is defined in?

Ah, I'm running Python 2.7.

LarsVegas
  • 6,522
  • 10
  • 43
  • 67
  • Better provide your code instead of letting us guess how it looks like –  Aug 08 '12 at 08:08
  • 1
    possible duplicate of [What does do?](http://stackoverflow.com/questions/419163/what-does-if-name-main-do) – jamylak Aug 08 '12 at 08:08
  • @Maulwurfn, How is the code of the class or the script itself relevant here? Or is it not clear what I'm doing wrong here? – LarsVegas Aug 08 '12 at 08:13

2 Answers2

6

The way to do what you want is to use an if __name__ == "__main__" block. See this question.

It's perfectly fine to define classes in scripts, but you cannot import the class without executing the script, because it is only by executing the script that you define the class. Class definitions are not a "compile-time declaration" in Python; they are executed in order just like everything else in the module. You should use an if __name__=="__main__" block to protect code that you don't want to be run when you import your file as a module.

Community
  • 1
  • 1
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
0

You should the if __name__="__main__: idiom to check whether Python is running the code or the code is being imported as a module.

Ramchandra Apte
  • 4,033
  • 2
  • 24
  • 44