Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Little confused with import python

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?

like image 739
Steven Avatar asked Jun 22 '13 19:06

Steven


1 Answers

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:

  • you never write an algorithm at the module's level; instead make it a function, and call that function
  • you never instantiate an object at the module's level; you shall embed it in the function, and call that function
  • if you need an object in several different functions, create a class and encapsulate that object in that class, then use it in your functions bound to that class (so they now are called methods)

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.

like image 69
zmo Avatar answered Sep 28 '22 14:09

zmo