2
\$\begingroup\$

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)
AJNeufeld
35.2k5 gold badges41 silver badges103 bronze badges
asked Dec 2, 2021 at 18:13
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Which commandment did you violate? Using os.path and pathlib in the same breath! pathlib is an object-oriented replacement to os.path.

 path = os.path.join(Path.cwd().resolve(), file)
 if os.path.isfile(path):
 with open(path) as f:

could be written as:

 path = Path.cwd().joinpath(file)
 if path.is_file():
 with path.open() as f:

or since you're starting at the current directory, simply:

 path = Path(file)
 if path.is_file():
 with path.open() as f:
answered Dec 2, 2021 at 18:55
\$\endgroup\$
2
  • \$\begingroup\$ I am using ruamel yaml in my own project, so I might be missremembering the details. I thought one could simply do content = yaml.load(path, Loader=SafeLoader) directly on the path without having to explicitly open it? \$\endgroup\$ Commented Dec 2, 2021 at 19:00
  • \$\begingroup\$ @N3buchadnezzar That may be true; I haven't used yaml at all. My answer focused on the mashup between os.path and pathlib, stopping just before the yaml.load(...) line for that very reason. \$\endgroup\$ Commented Dec 2, 2021 at 19:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.