Creating Python submodule

Viewed 1487

I want to create a tool called unifile for saving and opening files like this unifile.open.yaml("file.yaml").

This is my structure:

unifile
|
├-open
|    └--__init__.py
|
└-save
     └--__init__.py

Code that call my module:

import unifile
a = unifile.open.yaml("file.yaml")

open/init.py

import yaml
class open():
    def yml(self, file_path):
        try:
            with open(file_path, "r", encoding="utf-8") as yaml_conf:
                yaml_file = yaml.safe_load(yaml_conf)

            return yaml_file
        except OSError:
            print("Can't load yaml")

1 error if I import unifile always say:

module unifile has no atribute open

2 error in __init__.py I can't open file

[pylint] Context manager 'open' doesn't implement enter and exit. [not-context-manager]

3 Answers

Two issues, two answers.

First, you should add an init file in unifile. With this, Python will understand that unifile is a package with a sub package.

Second, open is a built-in function and you overwrite it by calling your class open. Change your class name and it should work.

  1. You are getting this error because unifile is not a package. There isn't any init.py file at the top level same as open and save. You also cannot call open.yml directly, because open is a class in package open, so either you will have to import open from open, create its instance and then call iml on that instance.

     from open import open
    
     a = open().yml('file.yml')
    
  2. You are getting this error, because you are trying to override an existing keyword in Python open which you should strictly prohibit doing. So you should name your class anything except a reserved keyword.

here adding solution to ur problem, make your project structure like this.

add unifile/__init__.py file in the unifile itself not in other modules.

enter image description here

then unifile/open/_open.py file content

import yaml

class Open():
    def __init__(self):
        pass
    def yml(self, file_path):
        try:
            with open(file_path, "r", encoding="utf-8") as yaml_conf:
                yaml_file = yaml.safe_load(yaml_conf)

            return yaml_file
        except OSError:
            print("Can't load yaml")

content of the unifile/__init__.py file

from .open._open import Open 

in terminal run the program like this

enter image description here

Also, It is better to create a object element first then proceed ahead.

Related