I come from a PHP (as well as a bunch of other stuff) background and I am playing around with Python. In PHP when I want to include another file I just do include
or require
and everything in that file is included.
But it seems the recommended way to do stuff in python is from file import
but that seems to be more for including libraries and stuff? How do you separate your code amongst several files? Is the only way to do it, to have a single file with a whole bunch of function calls and then import 15 other files?
Things are totally different between PHP and Python, and there are many reasons why.
But it seems the recommended way to do stuff in python is
from file import
but that seems to be more for including libraries and stuff?
Indeed, import
statements are for importing objects from another module to current module. You can either import all the objects of the imported module to current module:
import foo
print foo.bar
or you can select what you want from that module:
from foo import bar
print bar
and even better, if you import a module twice, it will be only imported once:
>> import foo as foo1
>> import foo as foo2
>> foo1 is foo2
True
How do you separate your code amongst several files?
You have to think about your code... That's called software design, and here are a few rules:
The only exception is when you want to launch a program from command line, you append:
if __name__ == "__main__":
at the end of the module. And my best advice would be to just call your first function afterwards:
if __name__ == "__main__":
main()
Is the only way to do it, to have a single file with a whole bunch of function calls and then import 15 other files?
It's not the only way to do it, but it's the best way to do it. You make all your algorithms into libraries of functions and objects, and then import exactly what you need in other libraries etc.. That's how you create a whole universe of reusable code and never have to reinvent the wheel! So forget about files, and think about modules that contains objects.
Finally, my best advice to you learning python is to unlearn every habit and usage you had while coding PHP, and learn those things again, differently. In the end, that can only make you a better software engineer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With