Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Import module from subfolder in Python

I want to import modules from subfolers in Python. It works from main.py to the subfolder, but not from subfolder to subfolder. Every folder has a __init__.py

This is how the folder structure looks like:
Folder structure

I’ve created a little "class diagram", to show how it needs to be imported:
Class diagram

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

main.py:

#! /usr/bin/env python

import os
from dotenv import load_dotenv
from os import path
from parser.Nfdump import Nfdump

def main():
    load_dotenv()
    
    p = Nfdump(os.getenv('flow_file_location'))
    p.Parse()

if __name__ == "__main__":
    main()

Nfdump.py

#! /usr/bin/env python

from types.Flow import Flow
from typing import NamedTuple
import ipaddress


class Nfdump:
    def __init__(self, file_location):
        self.file_location = file_location

    def Parse(self):
        ##parsing magic

Flow.py:

#! /usr/bin/env python
from typing import NamedTuple
import ipaddress

class Flow(NamedTuple):
    ip_source: ipaddress.ip_address
    port_source: int
    ip_dest: ipaddress.ip_address
    port_dest: int
    flags: str

Error thrown:

ModuleNotFoundError: No module named 'types.Flow'; 'types' is not a package

I am using Python 3 (3.10.2)

>Solution :

The reason for this error is that types is already a name used by Python for the standard library.

Rename your folder from types to something else.

https://docs.python.org/3/library/types.html


In addition, you will probably have to change your imports to contain the full path, and execute it inside of the folder containing flowscanner

from flowscanner.types.Flow import Flow
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading