If I am working interactively with 10 variables and wanted to pickle
them and reload them tomorrow using the same variable names, would there
be a direct way of doing it?
Thanks,
Darren 4 1357
On Tue, 27 Jul 2004, Darren Dale wrote: If I am working interactively with 10 variables and wanted to pickle them and reload them tomorrow using the same variable names, would there be a direct way of doing it?
Reminds me of my days in AppleSoft BASIC :)
Unfortunately, there is no quick & easy way to do this in Python, since
there is no easy way to differentiate unpicklable things (such as modules
and functions) from picklable ones (your variables), nor to make Pickle
gracefully ignore such objects. If you can get all your variable names
into a list, however, you could use this code: foo = 5 bar = 6 myvars = ['foo','bar'] import pickle pickle.dump(dic t([(n,vars()[n]) for n in myvars]),open('myvars' ,'w'))
[time passes]
import pickle vars().update(p ickle.load(open ('myvars'))) foo
5 bar
6
Pythonistas will cringe at my gratuitous use of vars(), but Python
currently provides no method of using getattr()/setattr() to get/set
module-level variables. getattr(__main_ _,...), anyone?
> Unfortunately, there is no quick & easy way to do this in Python, since there is no easy way to differentiate unpicklable things (such as modules and functions) from picklable ones (your variables), nor to make Pickle gracefully ignore such objects. If you can get all your variable names into a list, however, you could use this code:
Could you determine the picklable types using something like this? Its
kinda ugly, but maybe something related would work:
myvars = {}
for key in vars().keys():
myvar = vars()[key]
if str(type(myvar) ) == "<type 'module'>": pass
elif: str(type(myvar) ) == "<type 'function'>": pass
elif: str(type(myvar) ) == "<type 'unpicklable'>" : pass
else: myvars.update({ key:myvar})
pickle.dump(myv ars,open('myvar s','wb'),-1)
Maybe a try/except would be appropriate, but the pickle docs ay that an
unspecified number of bytes may have been written to the file before the
PicklingError exception is raised.
Further comments would be greatly appreciated.
On Wed, 28 Jul 2004, Darren Dale wrote: Could you determine the picklable types using something like this? Its kinda ugly, but maybe something related would work:
myvars = {} for key in vars().keys(): myvar = vars()[key] if str(type(myvar) ) == "<type 'module'>": pass elif: str(type(myvar) ) == "<type 'function'>": pass elif: str(type(myvar) ) == "<type 'unpicklable'>" : pass else: myvars.update({ key:myvar})
You can do this a bit more directly using the types module to check the
types (with a little bit of code restructuring):
from types import *
myvars = {}
for key,myvar in vars().items():
if not isinstance(myva r,(ModuleType,F unctionType)):
myvars[key]=myvar
A list comprehension would get you a nice, unreadable one-liner if it's so
desired:
from types import *
myvars = dict([(key,myvar) for key,myvar in vars().items() \
if not isinstance(myva r,(ModuleType,F unctionType))])
The problem with these types is there's no real guarantee what can be
pickled and what can't, and of those things that can be pickled, what
makes sense (functions can be pickled, but their code isn't stored).
There's currently no ispicklable() function
Maybe a try/except would be appropriate, but the pickle docs ay that an unspecified number of bytes may have been written to the file before the PicklingError exception is raised.
You could use dumps() instead of dump() for testing picklability before
picklation, though it smells of hackishness:
def ispicklable(ite m):
try:
pickle.dumps(it em)
except PicklingError:
return False
return True
Then you can just use ispicklable() in place of the 'not isinstance()'
mess I wrote.
I've done some poking though, and there a better way than that. It seems
all picklable objects define a __reduce__ method, so you could generalize
this check like this:
def ispicklable(ite m):
try:
item.__reduce__ ()
except KeyError,TypeEr ror:
return False
return True
Dunno if any of this helps; sorry if parts make no sense, I've retyped
parts of this a couple times :P
> I've done some poking though, and there a better way than that. It seems all picklable objects define a __reduce__ method, so you could generalize this check like this:
def ispicklable(ite m): try: item.__reduce__ () except KeyError,TypeEr ror: return False return True
I think this may only be true for new-style classes, or objects that
pickle "is unfamiliar with". I tried calling this method for strings,
dicts, lists, and it complains that these are all unpicklable.
object().__redu ce__() does work though.
I'll give it some thought. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Garett |
last post by:
Hello, I would like to be able to save source typed into the interpreter
to a file. Kind of like marshal, but I would like to have the file contain
the source so I can edit it later. Something like inspect.getsource() but
for source typed into the interpreter, not imported from a module. Is this
possible? Any ideas are greatly appreciated. -Garett
|
by: ohms377 |
last post by:
Dear python users,
In interactive mode, I was wondering if there is a way to list all
declared variables and functions (and from global workspace).
Thanks,
-frankie
|
by: Joshua Weir |
last post by:
Hi,
I have 2 questions:
1.
IF i create an object on the Page_Load event function of a specific aspx
page. Like so:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
|
by: WJ |
last post by:
I have three ASPX pages:
1. "WebForm1.aspx" is interactive, responsible for calling a web site
(https://www.payMe.com) with $$$. It is working fine.
2. "WebForm2.aspx" is non-interactive, a listener in my site to capture a
"STATUS_CD" returned by www.payMe.com. It is working fine.
3. "WebForm3.aspx" is interactive page, responsibe to display the STATUS
CODE "POSTED" by "WebForm2.aspx".
4. My goal is to use "WebForm2.aspx" to call...
|
by: Dave Moore |
last post by:
Hi All,
Here's my problem. I'm having trouble managing the additional variables
on the end of my URL. For example, I might have a URL like the following:
http://www.mydomain.com/index.php&option1=5&option2=7
It's the 'option' variables I'm having problems with. I would typically use
variables of this form to control various aspects of the current page.
However, the actual options present will be dependant on the current mode of
the...
| |
by: Mark Denardo |
last post by:
Hi, I need some expert GDI+ person to help me with my RoundOffImage
Function:
What I'm trying to do is take in an image, crop off the edges around an
ellipse region I set up, and then return the cropped image from the
function. I sort of have this working, but not thoroughly.
If I take the output image of this function and draw it on my form it shows
the clipped image as transparent as I am wanting it. But if I take that
image and...
|
by: Seymour |
last post by:
I created a module with the DictAdder subclass as follows:
class DictAdder(Adder):
def add(self, x, y):
new={}
for k in x.keys(): new=x
for k in y.keys(): new=y
return new
At the interactive prompt I then said: from Adder import *
|
by: andrewfelch |
last post by:
Hello all,
I'm using the metaclass trick for automatic reloading of class member
functions, found at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164
My problem is that if I
1) pickle an object that inherits from "AutoReloader"
2) unpickle the object
3) modify one of the pickled' object's derived class methods
4) reload the module holding the class
|
by: none |
last post by:
Hello,
IIRC, I once saw an explanation how Python doesn't have "variables" in
the sense that, say, C does, and instead has bindings from names to
objects. Does anyone have a link?
Thanks,
Ami
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |