Xian Li
Xian Li

Reputation: 13

How to import function from a sub-file within a folder (without having to refer to the name of the sub-file)

I have written a bunch of functions stored in different python files over the past years that I would like to dump into a folder and just use 'import folder' to call the functions from those python files.

So far, all the solutions I have read needs to either:

    from folder.pyfilename import func1 
    func1()

or

    from folder import *
    pyfilename.func1()

Does anyone know if it's possible to do something like this?

Upvotes: 1

Views: 407

Answers (2)

tdelaney
tdelaney

Reputation: 77337

You could add a file folder/__init__.py and have it do the subfolder imports.

__init__.py

from .prog1 import foo, bar
from .prog2 import baz

__all__ = ["foo", "bar", "baz"]

__all__ lists the variables that are imported by from foo import * so its not really all of the names, but it is all of the names the implementer thinks you should care about.

Now you can write programs that do

from folder import *

foo()

Upvotes: 1

Alfie Hanks
Alfie Hanks

Reputation: 61

Your question doesn't make too much sense to be honest, however you could do something like this:

    import folder.program as prog
    from folder import program2 as prog2
    prog.function()
    prog2.function()

In case you don't know, the as keyword is used to create an alias.

As far as I'm aware, you can't do what you want. You have to tell python which file the function is in.

I'm guessing you want to import the whole folder because it would take a while to add all the imports? I think you would just have to copy all the functions you want into one single file - or import each file/function as you already have done.

Upvotes: 1

Related Questions