hgl
hgl

Reputation: 2214

How to import relative module from __main__ in python

I have two file

foo.py
main.py

while executing python main.py, I want main.py to import foo.py.

I tried

from . import foo

But python complains

Attempted relative import beyond top-level package

I also tried

from foo import func_name

It works, but that means I can only directly import what get exposed. I want to use it like foo.func_name

Is it possible to import the whole module in a relative way (regardless what the current working directory is)?

Upvotes: 0

Views: 54

Answers (1)

kabanus
kabanus

Reputation: 25895

The script directory is already a part of the import path. Simply use

import foo

Upvotes: 4

Related Questions