Main Menu

search

You are here

Python: Functions & Importing

[last updated: 2021-08-08]
go to: Python home page
go to: Python: Programming Statements
-----

  • Define a Function:
    • Code to define a function starts with "def"
      followed by the function name,
      followed by "( )" that contain any parameters passed to the function,
      followed by a colon ":"
    • The statements that make up the body of the function follow, and must be indented from the "def" line
    • A "return" statement or an un-indented line will mark the end of a function definition
        Note: a return statement is good practice,
        since if eg. you have a null function with nothing in it other than perhaps a comment,
        it will fail with error if there's no return statement.
        (same applies - according to my trials - if you only have file open & close statements in the function)

    • For example:
        def calcFunc ():
          tempVar = 5
          return
  • Using a Function:
    • Using a function inside the program where it's defined:
      • call a function with:
        calcFunc()
      • The function call must be executed After the function is defined in your program.
    • Using a function in a different program (in the same directory):
        (Note: These procedures worked in both python 2.7.15 and python 3.5.3)
        Functions must be "imported" to use them in a different program:
        Suppose you have defined a function, eg. func01
        and it's defined (located) in eg. funcs.py
        and you want to use this function in a different program, eg. main.py
      • Put these lines into main.py:
        • import funcs
          then execute with:
          funcs.func01()
        • or:
          import funcs as F1 (where 'F1' is your choice of name/tag)
          then execute with:
          F1.func01()
        • or:
          from funcs import func01 (only imports the func01 function from funcs)
          then execute with:
          func01()
          • one source recommended using: from .funcs import func01
            but this failed with error something about "relative imports" and "parent not loaded"
        • or:
          from funcs import * (imports all functions defined in funcs)
          then execute the same, with:
          func01()
          • However: one note said this method failed with python 3.5.4...
    • Using a function in a different program (in a different directory):
      • (3.5.3) if funcs.py is located in a sub-directory myFuncs, then this worked:
        from myFuncs.funcs import *
        However I could not find an analogous syntax for directories above current directory...
      • ...
      • [stuff below here not tested...]
      • or:
        import sys
        print(sys.path) # shows your current sys path
        sys.path.append(" **Put here the directory where you have the file with your function** ")
        then execute with:
        from file import function
      • or:
        Add the path to the PYTHONPATH variable:
        export PYTHONPATH=$HOME/dirWithScripts/:$PYTHONPATH
      • or:
        import os
        os.chdir(" **Put here the directory where you have the file with your function** ")
        then execute with:
        from file import function
        then restore working directory:
        os.chdir(" **Put here the directory where you were working** ")
      • or:
        # some_file.py
        import sys
        # insert at 1, 0 is the script path (or '' in REPL)
        sys.path.insert(1, '/path/to/application/app/folder')
        import file
      • or:
        from application.app.folder.file import func_name
          Note: Just make sure folder also contains an __init__.py, this allows it to be included as a package.
          The init.py or __init__.py file can be an empty file. Its very existence tells Python to treat the directory as a package.
      • or (in summary?):
        First: import sys
        Second append the folder path: sys.path.insert(0, '/the/folder/path/name-folder/')
        Third Make a blank file called __ init __.py in your subdirectory (this tells Python it is a module):
          name-file.py
          name-folder
          __ init __.py
          name-module.py

        Fourth import the module inside the folder: from name-folder import name-module

      • or:
        import sys
        sys.path.append(pathToFolderContainingScripts)
        from scriptName import functionName #scriptName without .py extension
      • ...

    ----------------------------------------------------------------

  • Misc Notes to Edit:
    • If sub.py is just a collection of functions that you've defined,
      then you can import them and call them from main.py with this:
      import sub Note: Do NOT include the .py of your sub.py
      sub.func_to_call()
      Confirmed
    • If sub.py also contains statements,
      then they will be executed (once) when you do the import

    ---------------------------------------------------------------

.

.

.

eof