Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have python file that has a user interface, that mainly create objects of some class.
That file will be used by my colleagues, on their own computers.
In another file, from my computer, I'm willing to reach those objects that the first file generated.
What will be the best way to "save" the objects of the class, and then reach them from
my computer?
Thanks
What you want to do is have the script serialize the objects, and send them to your computer over the network.
As inspectorG4dget has said, you can use the pickle module to serialize your objects, and the requests library should be good for sending the objects from the client side.
On your machine, you would need a web-server/socket-listener, listening for the sent messages. You would deserialize them, and use them in some way after that.
Pickle or cPickle nicely handles saving object instances (as well as anything else); documentation here.
Two notes from when I fumbled through the a similar problem:
When you load a pickled object instance, you must have the object's class definition present in the namespace of the script/environment where you load.
Not everything can be pickled; I ran into this when saving objects that contained scipy spline instances. In your class definition, you can override the default behavior when pickling and unpickling in order to safely save and restore such attributes.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm writing a module which only contains functions. Is it good practice to put these inside a class, even if there are no class arguments and the __init__ function is pointless? And if so how should I write it?
There's no particular reason to force functions to go inside a class if there's no reason to make a class. A python sourcefile already provide a perfectly reasonable namespace for storing similar, related functions. The pypy implementation of the python programming language, for example, has many modules that don't have classes in them (for example, time).
You would want a certain data structure as a class, of course, but there are certain behaviors that are entirely independent of data structures, and putting them in a class would just add needless complexity.
It is good to build modules that contain a class for better organization and manipulation depending on how big the code is and how it will be used, but yes it is good to get use to building classes with methods in them. Can you post your code?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am reading Effective Python by Slatkin. In item 24, he talks about achieving polymorphism in python by using classmethod functions that play the role of constructors.
However, it is not clear to me why this is necessary. Why can we not achieve the same goal by simply using __init__ and overriding it in every derived class, the same way we're overriding the classmethod?
In his case, he has only one constructor per class, so why not use regular init for that purpose rather than classmethod?
You can see what's item 24 here, unfortunately details are missing:
http://ptgmedia.pearsoncmg.com/images/9780134034287/samplepages/9780134034287.pdf
More details here:
http://qiita.com/giwa/items/fd563a93825714cffd70
In the examples given in the book, the classmethod doesn't produce a single element. All different classes support the same classmethod (same signature) but what they do to produce the instances or how many they produce, is delegated to the class.
The PathInputData class, for example, produces inputs based on the config['data_dir'] configuration, using os.listdir() to read the all input files. You can imagine a DatabaseInputData class that provides the same generate_inputs() class method, but instead connects to a database and runs a SQL query. It'll look for different configuration. Etc.
You can't do this with the __init__ method; that's for initialising a single instance. If there are 0 instances to produce of the class, __init__ wouldn't even be called, but it still is a good idea to delegate the responsibility to find out how many instances must be produced to the class.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have some code in Python which generates a set of data structures (they may be represented by classes but no methods are needed).
This data structures may be extended or added new structures in future
I have some code in C++ on Android which knew about part of this data structures and their fields.
The only way to pass data structures is through serialization to file and then deserialize them
Binary format support is needed.
Mature implementations in Python and C++ are needed. BSD, MIT, Apache licenses are preferred.
Speed is not critical.
I have tried custom format but it is hard to extend it.
SAX-like parsers are too low level for such task.
The most important factor here is the file format to be passed on - whether you need to create a proxy class on the other side or if you simply need to read data on the other side, once the data format is known on the received side, the receiver side should know how to handle it.
Thus, it is best to use the data format which are well-known and widely used. Mostly for the reason of their widely-used virtue, such data formats would also normally have some 3rd party or build in library to help you creating your data structure files.
For this purpose, I will recommend you to use either JSON or XML data format. Python already have serializers for both:
XML: http://code.activestate.com/recipes/577268-python-data-structure-to-xml-serialization/
JSON : https://docs.python.org/3/library/json.html, http://www.diveintopython3.net/serializing.html, https://docs.python.org/2/library/json.html
You can also search some of other alternatives which I believe are also available apart from them.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've got a python script that is slowly consuming all of my memory (48GB). If I recall, python will perform garbage collection so there is no need for me to cleanup after myself?
for example:
class data_store:
dat1={}
dat2={}
dat3={}
class myclass ():
def mem_func(self):
self.x = data_store()
self.x.dat1 = (lots of data)
self.x.dat2 = (lots of data)
y = x.dat1 + 1
...
Most of my data is stored in data_store() temporarily before it is written out to files. I would think that this would be the source of the leak. Everytime mem_func() is called a new data_store() object is created and assigned to self.x. I assume that the old data_store() object would now be a candidate for the GC to delete. In addition, I would assume that y also be able to be deleted after mem_func completes.
The only other thing I can think of is that I am creating figures with matplotlib and saving them to a file. That is all done in one function but perhaps I need to delete the figure properly. Also, I have a sqlite db that is open the whole time where I am writing data but that is not alot of data. The image is much bigger.
You need to remember that GC only collects data that no pointer (variable) is pointing at it. In other words, as long as the memory is accessible via your variables, it won't be collected/freed.
So you need to assing None to the variables you don't need any more, or assign new data to the same variable names, if you don't need them any more.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Sometimes, when looking at Python code examples, I'll come across one where the whole program is contained within its own class, and almost every function of the program is actually a method of that class apart from a 'main' function.
Because it's a fairly new concept to me, I can't easily find an example even though I've seen it before, so I hope someone understands what I am referring to.
I know how classes can be used outside of the rest of a program's functions, but what is the advantage of using them in this way compared with having functions on their own?
Also, can/should a separate module with no function calls be structured using a class in this way?
A module is preferred when it is a collection of pure functions i.e. no shared state like module level variables. A big class is often used when there are multiple functions operating on a shared state.
In Python scripts, you will often see the pattern of the main function being just the instantiation of a class and calling a method for e.g youtube-dl. This is done for various reasons:
Can instantiate multiple objects without mixing state. It is easier to make it threadsafe.
Classes can be inherited or composed (for e.g. see BaseHTTPRequestHandler
Classes have more features than modules like constructors, iteration support etc.
In general, classes offer more power with slight added complexity. Some people prefer functions for simplicity esp in the case of one-time scripts. The tradeoff is upto the developer and both are valid options in Python.
A program often has to maintain state and share resources between functions (command line options, dB connection, etc). When that's the case a class is usually a better solution (wrt/ readability, testability and overall maintainability) than having to pass the whole context to every function or (worse) using global state.