Search code examples
pythonpippython-importpypi

How can I have my PyPI package run by just importing it, and not importing anything from it?


I have created my first PyPI package, but have a problem. I would like the user to be able to import the package, named chess-graph, and then run it straight away.

For example, the user can type in import chess_graph. Then, they could run the program straightaway with chart.graph(<link-to-file>).

However, when I try to do run the package this way, I cannot do so. Instead, I have to type in import chess_graph (after running pip install chess-graph) and then following that type from chess_graph import chart.

Is there any way for me to be able to have chart be imported along with chess_graph? This is how my directory looks like:

/pypi_chess

    /chess_graph

        __init__.py

        chart.py

        game_parser.py

    LICENSE

    README.md

    setup.py

My guess is that I could import the chart in the __init__.py file, however that does not work.

My __init__.py file looks like this:

from chess_graph import chart

print('test print')

When I run import chess_graph it prints test print, but if I try to straightaway type chart.graph(file), it says name: chart is not defined.

I know it is importing it, however, as chart is a big file and it takes a few seconds to import chess_graph.

How can I run the chart file just by importing the package?


Solution

  • With an __init__.py like that, you can do:

    import chess_graph
    
    ...
    
    chess_graph.chart.graph(file)