Darren Oakey
Darren Oakey

Reputation: 3604

how do I create a library that works as a common set of imports for python

I use jupyter notebook to do my job a lot of the time, so create several new notebooks a day to solve various different tasks. There are about 12 libaries - that I always import - and I always open another notebook at random, cut and paste the first cell into the new notebook

So there's a lot of duplication, and I'm wondering if I can avoid it in any way? What I really want is to do a line like:

   import common

and have a common.py library that looks something like this:

import re
import os
import pandas
import psycopg2
import datetime
import keyring
import pymssql

#
# code here to somehow bump it up to or expose it to the root scope - I thought this would work, but
# it doesn't
#
globals()["re"] = re

#
# my common functions etc
#
...

the idea being that I can just put "import common" at the top of every script instead of listing a bunch of individual modules - because when I copy from another, each one ends up subtly different because I add other ones and stuff over time.

NOTE: I know I could

Upvotes: 3

Views: 315

Answers (1)

mcsoini
mcsoini

Reputation: 6642

from imports import *

should work. This exposes the whole namespace of the imports module and you can just use e.g. pandas.DataFrame.

That said, I would keep copy and pasting all imports, for the sake of clarity.

Upvotes: 3

Related Questions