Python Forum

Full Version: import just one class from a file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all ! In a file called " __init__.py" I have many classes. I am only interested from the "class sudoku". In my "__main__.py" I write , at the top, "from __init__ import sudoku". That does not work. "from __init import **sudoku**", does not work.
"from __init__ import class sudoku"; None works. Thanks for your help.
Your explanation dos not make so much sense,so i make a example.
C:\Python36\sudoku_folder\
  |-- __init__.py
  |-- bar.py
  game\
    |-- __init__.py
    |-- sudoku.py
__init__.py files are blank,they help Python navigate the file tree.
# bar.py
def foo():
    return 42

if __name__ == '__main__':
    print(foo())
# sudoku.py
class Sudoku:
    def __init__(self, number):
        self.number = number

    def result(self, last_number):
        return last_number + self.number

if __name__ == '__main__':
    play = Sudoku(100)
    print(play.result(50))

Now can i test my package.
C:\
λ ptpython
>>> from sudoku_folder.game import sudoku

>>> play = sudoku.Sudoku(555) # Now do i access Sudoku class 
>>> play.result(100)
655

>>> # Assess the lonely foo() function
>>> from sudoku_folder import bar

>>> bar.foo()
42
Try to understand the basic how folder and files work in a package.
Can also edit __init__.py to shorten import statement,but that do i not take now.
Name of folder: sud
Contains: __pycache__, __init__.py, __main__.py
In __main__.py I wrote: from sud.__init__ import sudoku
No error appears.
Rename __main__.py to a normal name related to contend.
Only __init__.py shall have __ double underscore in you package folders.
Quote:from sud.__init__ import sudoku
__init__ shall never be part of import statement.

Take a step back,because you mess this up bye not understand how it work.
Look at my code one more time,take it for a test run.
Look at Packages documentation.
I think you are right for the name of __init__.py. But the author of the sudoku solver, did so. I am amazed to see that it is possible to work just on a class. If you want information on the sudoku, look at my thread "Continue SUDO project", in GUI forum. Thanks for your help.