Custom function to read file from current path in Python needs refactoring

Viewed 70

I had to write a custom function to load a yaml file from the current working directory. The function itself works and my intention was to write it in a pure fashion but my senior colleague told me that the way I wrote this function is utterly bad and I have to rewrite it.

Which commandment in Python did I violate? Can anyone tell me what I did wrong here and how a "professional" solution would look like?

from typing import Dict
import yaml
from yaml import SafeLoader
from pathlib import Path
import os


def read_yaml_from_cwd(file: str) -> Dict:

    """[reads a yaml file from current working directory]
    Parameters
    ----------
    file : str
        [.yaml or .yml file]
    Returns
    -------
    Dict
        [Dictionary]
    """
    path = os.path.join(Path.cwd().resolve(), file)
    if os.path.isfile(path):
        with open(path) as f:
            content = yaml.load(f, Loader=SafeLoader)
            return content
    else:
        return None

content = read_yaml_from_cwd("test.yaml")
print(content)
1 Answers

The significant parts of your function can be reduced to this:

import yaml
from yaml import SafeLoader

def read_yaml_from_cwd(file):
  try:
    with open(file) as f:
      return yaml.load(f, Loader=SafeLoader)
  except Exception:
    pass

In this way, the function will either return a dict object or None if either the file cannot be opened or parsed by the yaml loader

Related