Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

  • reference everything through common, which is bad because it changes the code and makes everything longer
  • put a function in common to sort of unpack everything and expose it to the root and call it from the root, which is bad because then I have to put in two lines, not just one
like image 839
Darren Oakey Avatar asked Jan 25 '26 07:01

Darren Oakey


1 Answers

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.

like image 93
mcsoini Avatar answered Jan 27 '26 19:01

mcsoini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!