0

not sure if I'm phrasing my question correctly but here goes. I've been using Python in a Juptyer Notebook on juptyer hub for one of my class. I've written many useful functions that I want to use to solve problems with. Right now, I have a code block at the beginning of my notebook with all the functions. Like this

import math
from fractions import Fraction

def ln(x):
    return math.log(x)
def lg(x):
    return math.log(x,2)

#Binomial Distribution
def binom(n,k,p):
    #binom(10,3,0.3), 0.266
    return math.comb(n,k)*p**k*(1-p)**(n-k)

def WrtFish():
    #Test WrtFish(), h,10,3,3 0.266
    poptype = input('Is the population haploid or diploid? Enter h or d.')
    rawpop = input('How many individuals are in the population?')
    if poptype == 'h':
        pop = int(rawpop)
    elif poptype == 'd':
        pop = 2*int(rawpop)
    rawgen1 = input('How many individuals in the current generation have the trait?')
    rawgen2 = input('How many individuals in the next generation are being inquired about?')
    i = int(rawgen1)
    j = int(rawgen2)
    p = i/pop
    return binom(pop,j,p)

It's gotten execessive, and I wanted to know if it's possible for me to make my own package for my own use. My ideal goal is to be able to chuck all of these in a package that I can update and import in new notebooks. e.i. I want to store all these functions in a notebook and be able to call them in a blank notebook where I can work out problems. I'd appreciate any insight you could give. Thank you!!!

  • So if I am getting it right, you want to have a master notebook containing all your useful functions, & import those functions in your new notebooks. In that scenario, this answer might help you. https://stackoverflow.com/a/50614132/13190386 – Jay Shukla Jan 08 '22 at 07:39
  • @JayShukla Just did the second method on that post with %run and it worked like a charm. Thank you! – chemclown21 Jan 08 '22 at 08:21
  • A better way is probably to make this a library. Basically put all of this in a .py file that resides in the same folder where all your notebooks are and then import the file by its name. – hypadr1v3 Jan 08 '22 at 08:30
  • 1
    @hypadr1v3 Yeah that's what i ended up doing based off the post Jay sent. I did ```$ jupyter nbconvert --to script name.ipynb``` in the terminal and ```%run -i name.py``` in the new notebook and it worked perfectly. Thank you – chemclown21 Jan 08 '22 at 09:00
  • if "name.py" includes only functions, class definitions, and constants you want to import, you could also use `import name` and then refer to the items you define in the module as `name.myfunc`, etc. See the [python docs on modules](https://docs.python.org/3/tutorial/modules.html) and [this realpython guide](https://realpython.com/python-modules-packages) for more info. – Michael Delgado Jan 09 '22 at 00:08

0 Answers0