Search code examples
pythonjupyter-notebookprivate

Private jupyter notebook


Is there a way to make unavailable for others jupyter notebook contents? I want to share notebook with others so it would perform the necessary actions but users couldn’t see the inside code.


Solution

  • If you save the code that's performing actions into an appropriately formatted .py file, and import from that file the calls you wish to perform - you could distribute this along with your notebook and encapsulate your user interface (the notebook) apart from your logic (the code in the .py file).

    For example, say in your notebook you have a function:

    def do_things(df):
        # do all the things
        # many lines of logic embedded in code
        ...
        return results
    

    To avoid displaying that code to your users, saqve it in a python file called privatethings.py and import it at the start of your notebook.

    import privatethings as pv
    

    As long as it exists in the same folder as your notebook, it will be imported and allow you to perform the actions as a one-line block of code.

    pv.do_things(df)
    

    A suitably clued-up user might figure out they can edit the .py file, so you'd have to tell them not to do that if they want the process to work as you've designed. But that would be their lookout.

    ---EDIT---

    Per conversation below, one (possibly dubious) way of fetching code from a distant resource might be to save it as some offline resource (say at a url, or in a scrambled text file) which can be fetched by the notebook.

    Then, using the compile function, the python source code can be compiled into a form that's exec-able, enabling you to access functions that have been imported from a (relatively) obscure source.

    Here's an example:

    file privatethings.py:

    def secret(string):
        return [s for s in string][::-1]
    

    Save this file at http://myloc.com/privatethings.py

    using requests:

    import requests
    
    url = 'http://myloc.com/privatethings.py'
    r = requests.get(url)
    source = r.text
    code = compile(source, '<string>', 'exec')
    exec(code)    # From here on, all functions in privatethings.py are available in this environment
    secret("test")
    
    >>> "tset"
    

    Of course, executing code like this is problematic in terms of trust (and might be considered unethical in some situations) but since it was discussed below, the above is a minimal example of how such a thing might be implemented.