Persisting functions typed into the shell

Wayne Harris wharris1 at protonmail.com
Sat Nov 12 10:56:25 EST 2022


On 12/11/2022 10:01, Stefan Ram wrote:
>   Many readers here know interactive Python sessions with
>   prompts like ">>>". But a "session" could be something else. 
>   One could imagine that when starting a new session, one
>   still sees all the variables and constants defined in 
>   preceding sessions.
> 
>   I have implemented something like a "restore()" and a "save()"
>   call. "restore()" will restore the names from the last "save()".
>   "save()" will look for user-defined names (it excludes certain
>   standard names and certain other names from my software) and
>   save them using the "shelve" package from the standard library.
> 
>   I you know "shelve" or have read the subject line, you can
>   guess what comes now:
> 
>   I cannot save user-defined functions this way!
> 
>   When a user types into the console:
> 
> |>>> def f():
> |...    print( "example" )
> |...
> 
>   he gives source code to shell and hopes that the shell will
>   cherish the memory of that function. But instead it acts as
>   if from now on it does not know the source code of "f"!
> 
>   So, there seems to be no way now to persist this function
>   to a file? as if by "save( f )" or something similar?
>   If not the source code, then maybe some other form?
> 
>   So much for the topic of "In Python, /everything/ is an
>   object"! There seem to be first and second-class objects:
>   Shelveable and non-shelveable objects.

Wow.  Could the dis module help at all?  Say by getting the bytes of the
compiled function and then saving them to a file, then reading them off
later and rebuilding the function with dis again?


More information about the Python-list mailing list