I was trying to understand use of slots in Python, so I created two classes, one with slots and one without it, then, I created about a million objects and print the size of both the objects:  &gt;&gt;&gt; class Foo(object): pass &gt;&gt;&gt; class Bar(object): __slots__ = () &gt;&gt;&gt; foos = [Foo() for f in xrange(1000000)] &gt;&gt;&gt; bars = [Bar() for b in xrange(1000000)] &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.getsizeof(foos) 4348732 &gt;&gt;&gt; sys.getsizeof(bars) 4348732   Surprisingly both the objects are of same size. So now I am confused why is it said that slots save memory ?  P.S. I tried this on Linux, Python 2.7  This is not duplicate of:   Here I want to know why the memory consumption in both the scenarios is same?
25235
What is the purpose of  in Python — especially with respect to when I would want to use it, and when not?
99004
This project I'm dealing with will read the size of free memory segments and size of processes from a text file and then will try to allocate a memory partition for each process using the first-fit, best-fit and worst-fit allocation algorithms. Below is the first part of the code I wrote. import sys  filename = sys.argv[1]  with open(filename, &quot;r&quot;) as file:         free_memory = file.readline().strip().split(',')         process_size = list(map(int, file.readline().strip().split(',')))         file = open(&quot;output.txt&quot;,&quot;w&quot;)    #---------------------------# #First-Fit Memory Allocation# #---------------------------#  file.write(f&quot;First-Fit Memory Allocation\n{'-'*60}\n&quot;)  file.write(f&quot;start =&gt; {' '.join(free_memory)}\n&quot;)  memory = list(map(int, free_memory))  memory_str = list(free_memory)  for process in process_size:         data = f&quot;{process} =&gt; &quot;         allocated = False         for index in range(len(memory)):                 if not allocated and memory[index] &gt;= process:                         memory[index] -= process                         memory_str[index] = memory_str[index][:-1*len(str(process))]                         memory_str[index] += f&quot;{process}*&quot;                           if(memory[index] != 0):                                 memory_str[index] += f&quot; {memory[index]}&quot;                         allocated = True                                  data += f&quot;{memory_str[index]} &quot;           if(not allocated):                 data = f&quot;{process} =&gt; not allocated, must wait&quot;                        file.write(data+'\n')
54034
I've been studying opengl es and an example I saw was using a "Pool" class to keep track of touch and keyboard events.  Could someone please explain how and why a pool class is needed. From what I was reading it had something to do with garbage collection and limiting the number of input classes that are made.   This all seems a little abstract to me, so if someone could please explain what is going on, I'd appreciate it, I'll pasted some code here:      public Pool(PoolObjectFactory &lt; T &gt; factory, int maxSize) {                     this.factory = factory;                  this.maxSize = maxSize;                  this.freeObjects = new ArrayList &lt; T &gt; (maxSize);          }                 public T newObject() {                 T object = null ;                 if (freeObjects.isEmpty())                         object = factory.createObject();                 else                          object = freeObjects.remove(freeObjects.size() - 1);                     return object;          }       public void free(T object) {                  if (freeObjects.size() &lt; maxSize)                          freeObjects.add(object);          }      PoolObjectFactory &lt;TouchEvent&gt; factory = new PoolObjectFactory &lt;TouchEvent&gt; () {           @Override          public TouchEvent createObject() {                   return new TouchEvent();          }       Pool &lt;TouchEvent&gt; touchEventPool = new Pool &lt;TouchEvent&gt; (factory, 50);      TouchEvent touchEvent = touchEventPool.newObject();      . . . do something here . . .      touchEventPool.free(touchEvent);   Thanks!
2266
In follow up to , it appears that some numbers cannot be represented by floating point at all, and instead are approximated.  How are floating point numbers stored?  Is there a common standard for the different sizes?  What kind of gotchas do I need to watch out for if I use floating point?  Are they cross-language compatible (ie, what conversions do I need to deal with to send a floating point number from a python program to a C program over TCP/IP)?
54033
I'm aware that shared objects under Linux use "so numbers", namely that different versions of a shared object are given different extensions, for example:   example.so.1 example.so.2   I understand the idea is to have two distinct files such that two versions of a library can exist on a system (as opposed to "DLL Hell" on Windows). I'd like to know how this works in practice? Often, I see that example.so is in fact a symbolic link to example.so.2 where .2 is the latest version. How then does an application depending on an older version of example.so identify it correctly? Are there any rules as to what numbers one must use? Or is this simply convention? Is it the case that, unlike in Windows where software binaries are transferred between systems, if a system has a newer version of a shared object it is linked to the older version automatically when compiling from source?  I suspect this is related to ldconfig but I'm not sure how.
866
In the following method definitions, what does the * and ** do for param2?  def foo(param1, *param2): def bar(param1, **param2):
38527
I'm just trying to streamline one of my classes and have introduced some functionality in the same style as the .  However, I'm a bit confused as to why __init__ is always called after __new__. I wasn't expecting this. Can anyone tell me why this is happening and how I can implement this functionality otherwise? (Apart from putting the implementation into the __new__ which feels quite hacky.)  Here's an example:  class A(object):     _dict = dict()      def __new__(cls):         if 'key' in A._dict:             print "EXISTS"             return A._dict['key']         else:             print "NEW"             return super(A, cls).__new__(cls)      def __init__(self):         print "INIT"         A._dict['key'] = self         print ""  a1 = A() a2 = A() a3 = A()   Outputs:  NEW INIT  EXISTS INIT  EXISTS INIT   Why?
40009
I have the following code that shows either a bug or a misunderstanding on my part.  I sent the same list, but modified over an ObjectOutputStream.  Once as [0] and other as [1].  But when I read it, I get [0] twice.  I think this is caused by the fact that I am sending over the same object and ObjectOutputStream must be caching them somehow.  Is this work as it should, or should I file a bug?   import java.io.*; import java.net.*; import java.util.*;  public class OOS {      public static void main(String[] args) throws Exception {         Thread t1 = new Thread(new Runnable() {             public void run() {                 try {                     ServerSocket ss = new ServerSocket(12344);                     Socket s= ss.accept();                      ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());                     List same = new ArrayList();                     same.add(0);                     oos.writeObject(same);                     same.clear();                     same.add(1);                     oos.writeObject(same);                  } catch(Exception e) {                     e.printStackTrace();                 }             }         });         t1.start();          Socket s = new Socket("localhost", 12344);         ObjectInputStream ois = new ObjectInputStream(s.getInputStream());          // outputs [0] as expected         System.out.println(ois.readObject());          // outputs [0], but expected [1]         System.out.println(ois.readObject());         System.exit(0);     } }
43
I am working on an application and one design approach involves extremely heavy use of the instanceof operator. While I know that OO design generally tries to avoid using instanceof, that is a different story and this question is purely related to performance. I was wondering if there is any performance impact? Is is just as fast as ==?  For example, I have a base class with 10 subclasses. In a single function that takes the base class, I do checks for if the class is an instance of the subclass and carry out some routine.   One of the other ways I thought of solving it was to use a "type id" integer primitive instead, and use a bitmask to represent categories of the subclasses, and then just do a bit mask comparison of the subclasses "type id" to a constant mask representing the category.  Is instanceof somehow optimized by the JVM to be faster than that? I want to stick to Java but the performance of the app is critical. It would be cool if someone that has been down this road before could offer some advice. Am I nitpicking too much or focusing on the wrong thing to optimize?
34575
I'm trying to work through the problems on  but I keep running into a couple of problems.  The first is a question of storing large quanities of elements in a List&lt;t&gt;. I keep getting OutOfMemoryException's when storing large quantities in the list.  Now I admit I might not be doing these things in the best way but, is there some way of defining how much memory the app can consume?  It usually crashes when I get abour 100,000,000 elements :S  Secondly, some of the questions require the addition of massive numbers. I use ulong data type where I think the number is going to get super big, but I still manage to wrap past the largest supported int and get into negative numbers.  Do you have any tips for working with incredibly large numbers?
18053
What is the difference between new/delete and malloc/free?  Related (duplicate?):
86980
I've only just started studying the Blender Python API. I'm writing a script (see below) to automate something I've done by hand : joining two adjacent cubes and cleaning up the resulting mesh.   After joining and removing doubles, I expect to have 12 vertices instead of 16 in the resulting object. In the Info header, this seems to be the case, but when I print to the windows terminal I still see 16. Also I do see the output from remove_double(), here's a screenshot :    So what's wrong here ? What is the right way to access an object's mesh, and count its vertices ?  Joao  import bpy  # Create two adjacent cubes and join them bpy.ops.mesh.primitive_cube_add(location=(1,0,0)) ob = bpy.context.object bpy.ops.mesh.primitive_cube_add(location=(3,0,0)) ob.select = True bpy.ops.object.join()  # Expect 16 vertices, 24 edges, 12 faces result = bpy.context.object print(str(len(result.data.vertices)))  # Go to edit mode, remove double vertices bpy.ops.object.mode_set(mode = 'EDIT') bpy.ops.mesh.remove_doubles()  # Expect 12 vertices, 20 edges, 11 faces result = bpy.context.object print(str(len(result.data.vertices)))
222
In several C++ examples I see a use of the type size_t where I would have used a simple int. What's the difference, and why size_t should be better?
80428
I have a class like this:  public class myClass {   public List&lt;myOtherClass&gt; anewlist = new List&lt;myOtherClass&gt;;    public void addToList(myOtherClass tmp)   {     anewList.Add(tmp);   }  }   So I call "addToList" a hundred times, each adding a unique item to the list.  I've tested my items to show that before I run the "addToList" method, they are unique.  I even put a line in to test "tmp" to make sure it was what I was expecting.  However, when I do this (lets say myClass object is called tmpClass):  int i = tmpClass.anewList.Count(); for (int j = 0; j&lt;i; j++) {    //write out each member of the list based on index j... }   I get the same exact item, and it's the last one that was written into my list.  It's as if when I add, I'm overwriting the entire list with the last item I've added.    Help?  This makes no sense. I've also tried List.Insert, where I'm always inserting at the end or at index 0.  Still no dice.  Yes, I'm doubly source my indexing is correct and when I do my test I'm indexing through each of the elements.  :)  UPDATE: Okay, I tried this and still had the same problem:  foreach(myOtherClass tmpC in tmpClass.anewList) {         Console.WriteLine(tmpC.theStringInMyClass.ToString()); }   and still for each of the 100 items, I got the same string output... I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with.  -Adeena    Okay, I tried this and still had the same problem:  foreach(myOtherClass tmpC in tmpClass.anewList) {     Console.WriteLine(tmpC.theStringInMyClass.ToString()); }   and still for each of the 100 items, I got the same string output...  I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with.  -Adeena
8925
Suppose I have a python object x and a string s, how do I set the attribute s on x? So:  &gt;&gt;&gt; x = SomeObject() &gt;&gt;&gt; attr = 'myAttr' &gt;&gt;&gt; # magic goes here &gt;&gt;&gt; x.myAttr 'magic'   What's the magic? The goal of this, incidentally, is to cache calls to x.__getattr__().
18926
I'm trying to understand the use of super(). From the looks of it, both child classes can be created, just fine.   I'm curious to know about the actual difference between the following 2 child classes.  class Base(object):     def __init__(self):         print "Base created"  class ChildA(Base):     def __init__(self):         Base.__init__(self)  class ChildB(Base):     def __init__(self):         super(ChildB, self).__init__()  ChildA()  ChildB()
87503
I always read that it is recommended to set objects to nothing, once I am done with them. But I normally use them only in functions inside forms.  Isn't the reference lost and memory released when the function scope is left, regardless of setting objects to Nothing?   i.e. is it really necessary to do:  Set db = Nothing Set record_set = Nothing