[Tutor] Alternative to importing

Alan Gauld alan.gauld at yahoo.co.uk
Sun Oct 3 18:45:39 EDT 2021


On 03/10/2021 16:21, Julius Hamilton wrote:

> Is there any alternative to importing a Python script in another script for
> the methods defined in it, where Python when executing one script will just
> automatically look in the enclosing folder for any other Python scripts,
> and check them for methods? 

That would be a really, really bad idea! Imagine the folder full of
scripts, potentially many of them with functions of the same name.
Which one does python decide to executer? The first one it finds?
Then a week or two later the same program runs but a few new scripts
have been added. Now it runs a completely different function!

And having picked a function what happens if that function calls
another function in a different module. Does Python now search
all the scripts to see if it can find that new function?
And what about global variables. If it just runs a random function
what happens to the names imported by that functions module?
Does it run the whole module or just the function?

It would rapidly descend into utter chaos. That's why we use
imported modules, to control the namespaces and make sure that
every function has the environment it needs to work properly.

You could argue that we could create a folder for the project
and only have the scripts swe need. But then we need to ensure
that function names are unique within, not just a file, but
the whole folder. And how would reuse work? You'd need to copy
the reused modules into every project folder. And what happens
when you fix a bug? You need to find every copy and fix it
in every one! That completely defeats the purpose of reusable
modules.

> python -“importall” runscript.py? Or some other way of eliminating import
> statements?

Why would you want to? imports and modules are one of the
most important tools for controlling the complexity of
Python projects. By removing that you have code anarchy.
Almost everything we do in software engineering is designed
to limit and control access to code and hide the details
away, inside packages, modules, classes, functions and
data structures. We don't want to expose things, we
want to hide them and only expose the things we really
need. It's what keeps us sane and our code maintainable!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list