Python Forum
Conditional importing inside a function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Conditional importing inside a function
#1
I would like to have a file "functions.py" where I collect functions that might be usefull.
Different functions may require different imports. Instead of importing them all at the beginning I would like each function to only import if it has not already been imported.
I have tried -
#!/usr/bin/env python3
"""
Reuseable functions
"""

import sys

def filesize(url):
    """
    Reports size of file pointed to by url.
    """
    if "os" not in sys.modules:
        import os

    return os.path.getsize(url)
My IDE warns me that "os" after "return" is an unresolved reference.
Obviously the scope of the "import os" is limited to the if block.

Is there a way of making the "import os" global?
Reply
#2
The name os is a local variable in function filesize() because you have import os in the function's body. It doesn't matter whether the import is within an if block or not. On the other hand at runtime the import statement is not executed if 'os' is already in sys.modules and the local variable os is used prior to initialization and that's an error.

You can simply write
 
def filesize(url):
    """
    Reports size of file pointed to by url.
    """
    import os
    return os.path.getsize(url)
One of the first things the import statement does is checking if the module is already in sys.modules, so it is unecessary to do it yourself. Just import the module.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  with open context inside of a recursive function billykid999 1 573 May-23-2023, 02:37 AM
Last Post: deanhystad
  How do I call sys.argv list inside a function, from the CLI? billykid999 3 788 May-02-2023, 08:40 AM
Last Post: Gribouillis
  Importing a function from another file runs the old lines also dedesssse 6 2,541 Jul-06-2021, 07:04 PM
Last Post: deanhystad
  How to make global list inside function CHANKC 6 3,081 Nov-26-2020, 08:05 AM
Last Post: CHANKC
  Parameters aren't seen inside function Sancho_Pansa 8 2,888 Oct-27-2020, 07:52 AM
Last Post: Sancho_Pansa
  Creating function inside classes using type wolfmansbrother 3 2,324 Mar-20-2020, 01:21 AM
Last Post: wolfmansbrother
  Animate graph nodes inside a function adamG 0 2,943 Sep-23-2019, 11:18 AM
Last Post: adamG
  How to pass a dictionary as an argument inside setup function of unittest nilaybnrj 1 3,205 May-11-2019, 03:18 AM
Last Post: keames
  function 2 inside function 1 parameters SheeppOSU 4 2,848 Apr-20-2019, 09:34 PM
Last Post: snippsat
  Trouble on importing function from astropy library samsonite 4 3,697 Mar-21-2019, 12:18 PM
Last Post: samsonite

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020