python code organisation

Started by
1 comment, last by Oluseyi 18 years, 8 months ago
Hi all Im starting on a new project this spring with is a small c++ 2d engine that I am going to interface with python. I know it is possebly to just use python with ie. PyGame for this task but I really want to learn how to interface it propperly. *Im thinking of rewriting my 3d engine with a interface to python.* Now I have as everyone else tried some python, I like the coding style and such. the real question is that I wonder: "How is large amounts of python code strucured?" In C++ we got the .cpp/.h relationship, how is this in python? Do you use a .py file and declare some stuff there or is it like writing a huge .h file in cpp? Or is there some mambo jabo magic that I haven't thought of? Also do you have 1 file per class or do you throw all your classes into one giant pice of a file? I noticed that thats a lot of question but I recon someone with a bit experience in python should be able to asnwer these without to much trubble.
- Me
Advertisement
In python you write modules, .py files, which are roughly analogous to a combined .h and .cpp file. When binding it to C++ you also expose modules from the C++ code, though they are bundles of C++ functions and objects rather than bundles of python functions and objects.
Quote:Original post by CoMaNdore
Do you use a .py file and declare some stuff there or is it like writing a huge .h file in cpp? Or is there some mambo jabo magic that I haven't thought of? Also do you have 1 file per class or do you throw all your classes into one giant pice of a file?

Just as C++ places no restrictions on how, exactly, you organize your code, so Python lets you organize your code as you see fit. Python modules can represent more than just a class, though; they are more analogous to C++ namespaces, or, even better, Perl packages. Many Python modules actually do nothing more than import and initialize a series of other modules, for the sake of end user convenience. A module with a function named <modulename>_init will have that function automatically executed when imported, just as a module directory with a file named __init__.py will have that script automatically executed. This is a great way to precompute certain data and ensure all the prerequisites of your own module are fully available.

Reference:
The import statement.
Built-in package support in Python 1.5 (and later).


One last thing: it is often found to be easier to extend Python with C++ code - ie, write a Python extension module in C++ - than to embed Python into C++. If you find yourself butting against numerous difficulties with one of extending or embedding, evaluate the implications of the other approach.

Happy hacking.

This topic is closed to new replies.

Advertisement