[Tutor] sharing a small script someone may find of use

Cameron Simpson cs at cskk.id.au
Fri Aug 12 22:35:48 EDT 2022


Ooooh, feedback!

On 13Aug2022 01:53, nathan tech <nathan-tech at hotmail.com> wrote:
>import time
>import importlib
>
>slist=[]
>
>file=input("What file should I read?")
>
>modules=[]
>
>f=open(file, "r")
>data=f.readlines()
>f.close()

The standard way to write this is:

    with open(file) as f:
        data = f.readlines()

or (giving that iterating a text file produces lines):

    with open(file) as f:
        data = list(f)

but even more common is, since text files iterate lines:

    with open(file) as f:
        for x in f:

>for x in data: # get the list of modules and remove any end of line for 
>x in data: # get the list of modules and remove any end of line 
>characters
>    if(x.startswith ("import") or x.startswith("from")):

This is a little loose, eg code like this:

    imported_modules = []

would match this test. Had you considered:

    words = x.split()
    if words and words[0] in ("import", "from"):

>        if(word[1] not in modules):
>            modules.append(word[1].strip("\n"))

I'd assign the module name to a variable:

    module_name = words[1]
    if module_name not in modules:
        modules.append(module_name)

Your modules are a list. That involves a linear code to scan it.  
Admittedly, itis likely to be quite a short list, but a set works 
better. Earlier in the code:

    modules = set()

then the same test.

    if module_name not in modules:
        modules.add(module_name)

But it looks like you're just accruing a unique collection of module 
names. Sets do that for free! So just:

    modules.add(module_name)

with no if-statement at all.

>print("Found "+str(len(modules))+" modules.")

print() converts its arguments to str for you. This is easier to write 
and read:

    print("Found", len(modules), "modules.")

>for x in modules:
>    start=time.time()
>    r=importlib.import_module(x)

Not using "r"?

>    if(time.time()==start): # probably cached

This is dodgy. A slow system (particularly a slow hard drive) or a very 
high res time.time() function will fail this test.

>        importlib.reload(r)

You can inspect what's imported directly:

    import sys
    if module_name in sys.modules:
        # already imported

You can probably just delete things from there, too.

What about:

    if module_name in sys.modules:
        del sys.modules[module_name]
    start = time.time()
    importlib.import_module(module_name)
    end = time.time()
    times[module_name] = end - start

Then you can sort times.items() by name or time or whatever.

At least brackets remove ambiguity.

All the above intended as positive feedback.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list