Reputation: 10686
Why does python use modules, instead of just including the module functions in the main language. It would be very useful and pretty easy, especially for the main ones such as random, re, and os. If Python preaches simplicity and minimalist, why do you have to write in extra lines of code?
Upvotes: 1
Views: 609
Reputation: 2832
Memory and speed efficiency
Objects that have been created (and everything is an object in Python) occupy the memory allocated to the Python interpreter process. When you import a module, its code is executed, resulting in the creation of many objects (functions, classes, data, etc.), most of which must persist in memory to be useful. By separating functionality into logically distinct modules, we allow programs to devote their memory only to objects providing the functionality they need.
If everything were built-in, you would have a huge chunk of memory devoted to all the classes, functions, and other objects of the entire standard library, less than 1% of which would actually be useful to the average program. Furthermore, you would waste time executing all the code that creates all these objects, every time the interpreter starts.
Upvotes: 4
Reputation: 12486
1) Zen of Python #19: "Namespaces are one honking great idea -- let's do more of those!"
Named modules are good because they eliminate any chance of a collision between functions with the same name. If everything was a builtin, then os.error()
would collide with logging.error()
(and heaven forbid you try to define your own function called error()
!)
Ditto the builtin int()
function and the random.int()
function. You would have to write the latter as random_int()
, which is just as much typing as the module syntax. Why not make the namespaces explicit and use modules?
This is the same reason the syntax from os import *
is frowned upon - it pollutes your namespace and introduces the chance for exciting name collision errors.
2) Who decides what's a builtin and what's a module?
Most of the programs that you personally write involve os
and re
. Personally every script I've written in the last three months has involved sqlite3
, csv
and logging
. Should those be included as builtins for every program that any Python programmer ever writes?
After a while your list of builtins gets to be bigger than Ben Hur.
Upvotes: 15