Python Forum
Python code keeps duplicating information - OOP ( Could be related to shallow copy? )
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python code keeps duplicating information - OOP ( Could be related to shallow copy? )
#1
never mind, asked a friend.
Reply
#2
No, Python doesn't duplicate objects if you mean the connection between classes <> Instances.

Example:

from sys import getsizeof

class Foo:
    pass


print(f"Class        -> {getsizeof(Foo)}")
print(f"Foo-Instance -> {getsizeof(Foo())}")
Output:
Class -> 1072 Foo-Instance -> 48
(Python 3.10.4)
As we can see, the instance needs only 48 bytes in memory. The instance has a reference to the class Foo, which is only once in memory. The class Foo itself consumes much more memory because the whole logic is done there.

To make the class and the resulting instance smaller, you could use __slots__.

from sys import getsizeof

class Foo:
    __slots__ = ()


print(f"Class        -> {getsizeof(Foo)}")
print(f"Foo-Instance -> {getsizeof(Foo())}")
Output:
Class -> 904 Foo-Instance -> 32
Python preallocates integers from -5 to 256. If the code uses one of these values, they exist only once in memory.

r = range(-10, 260)
for a, b in zip(r,r):
    if a is not b:
        print(a)
Output:
-10 -9 -8 -7 -6 257 258 259
The printed numbers are outside the range of preallocated integers.
Those integers, which are printed, are copies. They exist twice for a short time in memory, until the garbage collection deletes the objects after they are no longer required.

Another example: Modules
If you import a module, its content is parsed, executed and cached in sys.modules.
Importing the module again, will use the already imported module from cache.

Python does much to reduce the memory footprint, but in general, a dynamic Language consumes more memory as a compiled language.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to copy a file to another location? Python 2.7 rcmanu95 1 1,443 Jul-19-2020, 05:49 AM
Last Post: ndc85430
  Framework Django duplicating objects in databases-table!? tavaresdavi677 1 3,623 Dec-12-2016, 07:43 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020