vaer-k
vaer-k

Reputation: 11773

In Python, can I make another module's functions available to users importing my module?

I use functools and itertools in pretty much every module. I find them so essential that I'm annoyed that I have to import their functions in every module I write. I'd like to create a module, let's call it mytools that imports all of the functions from functools and itertools and makes their functions directly available to any module that imports mytools.

I'm specifically interested in manipulating the import system in this way, so please avoid sidestepping this approach in solutions just for the sake of making functools and itertools easily available.

Upvotes: 1

Views: 128

Answers (2)

user4805123
user4805123

Reputation:

You could create your own class that imports and defines them as being self names:

import itertools
import functools


class MyTools(object):
    def __init__(self):
        self.itertools = itertools
        self.functools = functools

You would then just have to import the file containing this class:

from mytools.py import MyTools
mytools = MyTools()

print(mytools.functools.partial)

Upvotes: 0

Patrick Haugh
Patrick Haugh

Reputation: 61063

Create a directory mytools and add it's parent directory to your python path. Inside that directory create a file __init__.py with

from functools import *
from itertools import *

Then from other files you can do

import mytools
print(mytools.partial)
# <class 'functools.partial'>

Upvotes: 2

Related Questions