Best practices regarding paths stored and retrieved from .env in python modules

Viewed 201

I am using a .env file to store paths, such as an input data path, output data path, etc. I am using the library dotenv to retrieve these paths and a config.py script to get these paths into the correct form for my project. I import config.py into my other modules, and therefore all of my paths are the same for all the modules within the package, and if anything changes, I only make that change once in the .env file. All of this is working correctly, and I have no problems here.

My question goes like this: Within a single module, I usually have several functions. A typical project involves defining something like main(), run(), formatfunc(), domathfunc(), movecomplexstuffoutofthewayfunc(), exportfunc(), etc.

Is it better to

  • A) define a path variable once in main and then pass it around to all the functions, or
  • B) retrieve the path variable in each function, and not bother passing it around?

A)

import config
def main():
  paths = config.getpaths(#returns dict of paths)
  datapath = paths['DATA']
  outpath = paths['EXPORTS']
  y = 'foo'    
  x = domathfunc(y, datapath)
  formatted = formatfunc(x, y, outpath)
  return formatted

def domathfunc(y, datapath)
   z = getdatafrom(datapath)
   results = mathematics(y, z)
   return results

def formatfunc(x, y, outpath)
   pretty = prettify(x, y)
   saveit(pretty, outpath)
   return pretty

or B)

import config
def main():
  y = 'foo'    
  x = domathfunc(y)
  formatted = formatfunc(x, y)
  return formatted

def domathfunc(y)
   paths = config.getpaths(#returns dict of paths)
   datapath = paths['DATA']
   z = getdatafrom(datapath)
   results = mathematics(y, z)
   return results

def formatfunc(x, y)
   paths = config.getpaths(#returns dict of paths)
   outpath = paths['EXPORTS']
   pretty = prettify(x, y)
   saveit(pretty, outpath)
   return pretty

In the actual work, there are a lot more functions, and I want to decide at the start of my project, do I pass the parameter for the path variable every time, or retrieve it every time? Does the possibility of having to change every function, should something change in the retrieval system become more important than reducing the number of parameters to reduce confusion?

1 Answers

It is better when you can test functions, main should be the dirtiest place in your code.

By dirty, I mean it applies an algorithm and uses functions in a specific scope.

Therefore A is better, because you can write tests for each function without running main.

Related