python: making your own interned type

Status
Not open for further replies.

Tiibiidii

Smack-Fu Master, in training
85
interning/recycling of objects makes sense only for values, that is: for objects that are immutable

otherwise, interning could be kinda like creating singletons and always reuse them (but this would get unwieldy quickly)

This might be interesting

afaik, string and integers interning is an implementation detail (and it varies between different python implementations)

What you're probably interested into, is avoiding memory allocations

This should be relevant

And also things like the array module might help you.

But if you need truly fine grained control of the memory, and creating extensions with CFFI (or the CPython api) is out of place, Python is probably not a good choice for the problem
 

DavlinLotze

Ars Scholae Palatinae
830
[url=http:/civis/viewtopic.php?p=26414851#p26414851:3u1e9tfy said:
bk0[/url]":3u1e9tfy]My first impression is that you are overthinking memory management--this is Python, focus on the algorithms and let memory do what it does unless you hit an obvious constraint--but it's hard to tell without a specific example.

Well, if I could ignore it at this phase, I would, but there's two problems:
1) If there's some way I can arrange things at an earlier stage - without the recycling implemented - that would prevent me from having to rewrite a bunch of code and interfaces later, I'd like to know.
1a) (Optimally, I'd like a system where I can just turn the interning on or off, or somewhere in between with just a change of a few variables - that would allow me to compare CPU/memory usage patterns, or tune it according to a particular usage case.)
2) I foresee my program depending on interning for more than just reducing memory footprint. It would allow me to make changes to just one object and have it take effect broadly instead of having to walk/search some huge complex tree and change each matching object.


[url=http:/civis/viewtopic.php?p=26414851#p26414851:3u1e9tfy said:
bk0[/url]":3u1e9tfy]Define "semantically equivalent" (preferably with pseudocode).

For any two instances a and b of class C, a == b if and only if a.some_core_attribute == b.some_core_attribute. (And, of course a == b if a is b or if a.some_core_attribute is b.some_core_attribute; these are a quicker check, since some_core_attribute may be complex.)

While, for the bulk of the processing, having one copy each of an instance of C is good enough, I foresee situations where it would be handy to have separate copies of them in different segments of the program - each copy with different extended attributes.
 

bk0

Ars Tribunus Militum
1,801
[url=http:/civis/viewtopic.php?p=26425715#p26425715:3cx197lq said:
DavlinLotze[/url]":3cx197lq]
[url=http:/civis/viewtopic.php?p=26414851#p26414851:3cx197lq said:
bk0[/url]":3cx197lq]My first impression is that you are overthinking memory management--this is Python, focus on the algorithms and let memory do what it does unless you hit an obvious constraint--but it's hard to tell without a specific example.

Well, if I could ignore it at this phase, I would, but there's two problems:
1) If there's some way I can arrange things at an earlier stage - without the recycling implemented - that would prevent me from having to rewrite a bunch of code and interfaces later, I'd like to know.
1a) (Optimally, I'd like a system where I can just turn the interning on or off, or somewhere in between with just a change of a few variables - that would allow me to compare CPU/memory usage patterns, or tune it according to a particular usage case.)
2) I foresee my program depending on interning for more than just reducing memory footprint. It would allow me to make changes to just one object and have it take effect broadly instead of having to walk/search some huge complex tree and change each matching object.


[url=http:/civis/viewtopic.php?p=26414851#p26414851:3cx197lq said:
bk0[/url]":3cx197lq]Define "semantically equivalent" (preferably with pseudocode).

For any two instances a and b of class C, a == b if and only if a.some_core_attribute == b.some_core_attribute. (And, of course a == b if a is b or if a.some_core_attribute is b.some_core_attribute; these are a quicker check, since some_core_attribute may be complex.)

While, for the bulk of the processing, having one copy each of an instance of C is good enough, I foresee situations where it would be handy to have separate copies of them in different segments of the program - each copy with different extended attributes.

Class properties?

Code:
class DataObject:
    invariant_property = "yo"

    def __init__(self, variant_property):
        self.variant_property = variant_property


a = DataObject("Spam")
b = DataObject("Eggs")

print(a.invariant_property)  # "yo"
print(a.variant_property)    # "Spam"
print(b.invariant_property)  # "yo"
print(b.variant_property)    # "Eggs"

DataObject.invariant_property = "holy crap"

print(a.invariant_property)  # "holy crap"
print(b.invariant_property)  # "holy crap"
 

DavlinLotze

Ars Scholae Palatinae
830
[url=http:/civis/viewtopic.php?p=26426247#p26426247:3b53hced said:
bk0[/url]":3b53hced]
Class properties?
Sorry if I was unclear, but you misunderstand. There are no invariant class properties.
More like this:
Code:
class DataObject:

    def __init__(core, **exattr):
        self.core = core
        for key in exattr:
         self.__dict__[key] = exattr[key]  # (Obviously more validation than this.)


a = DataObject(alpha, pic="alpha.ico")
b = DataObject(beta, text="beta", pic=DEFAULT)
a2 = DataObject(copy_of_alpha, vector="Alpha.svg", text="alpha", category="system")
a3 = DataObject(alpha)

assert(a == a2 == a3)
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Well, if I could ignore it at this phase, I would, but there's two problems:

Seems very premature optimisation-like to me. Unless you *know* allocation (or pointer indirection for a field based equality test[1]) [edit]is going to be a problem[/edit] then just implement it to start with and see how it goes down.

I'm not familiar with the python eco-system but I presume there are some decent profilers out there for it?

Interning can be a net loss, it may force the memory layout of values to be poorly distributed for long term behaviour verses their initial creation (vice versa it can sometimes be a significant part of their benefit) compared to letting the GC try to deal with short lived objects.

Unless you already know that allocations on your hot paths are a no-no[2] why are you assuming this will be worth the complexity?

1. If so you are almost certainly using the wrong language for the job
2. This is reasonable, though again I would argue python/java and many others make for very poor languages if this is the case
 

dmitriyk

Ars Tribunus Angusticlavius
8,804
A bit out of order, but...

[url=http:/civis/viewtopic.php?p=26425715#p26425715:3rx2xor7 said:
DavlinLotze[/url]":3rx2xor7]
2) I foresee my program depending on interning for more than just reducing memory footprint. It would allow me to make changes to just one object and have it take effect broadly instead of having to walk/search some huge complex tree and change each matching object.
1) That's not interning. Suppose you instantiate two objects, a and b, such that a.some_core_attribute != b.some_core_attribute, and then change b such that a.some_core_attribute == b.some_core attribute. What the hell happens to the interned objects? Consider the reverse case as well. Interning and mutability are mutually exclusive.
2) I really hope you're writing a single-threaded application.

1a) (Optimally, I'd like a system where I can just turn the interning on or off, or somewhere in between with just a change of a few variables - that would allow me to compare CPU/memory usage patterns, or tune it according to a particular usage case.)
This fundamentally conflicts with your point number 2.

1) If there's some way I can arrange things at an earlier stage - without the recycling implemented - that would prevent me from having to rewrite a bunch of code and interfaces later, I'd like to know.
Again, this fundamentally conflicts with point number 2. If you're relying on behavior described therein, the system will have to be designed and implemented with that functionality in mind. That behavior is more significant than just a memory optimization and will be difficult to implement later.

If your some_core_attribute is complex to calculate, just hash it on update and check the hash on equality comparison. With proper interning, you'd have to perform that some_core_attribute calculation on every object instantiation anyway (and have to transition to immutable objects).
 
[url=http:/civis/viewtopic.php?p=26425715#p26425715:3mntzro3 said:
DavlinLotze[/url]":3mntzro3]
[url=http:/civis/viewtopic.php?p=26414851#p26414851:3mntzro3 said:
bk0[/url]":3mntzro3]Define "semantically equivalent" (preferably with pseudocode).


For any two instances a and b of class C, a == b if and only if a.some_core_attribute == b.some_core_attribute. (And, of course a == b if a is b or if a.some_core_attribute is b.some_core_attribute; these are a quicker check, since some_core_attribute may be complex.)

Maybe I'm missing something here, but can't you use Python's rich comparison methods (__eq__, __ne__, __le__, etc.) to handle this case?
 

bk0

Ars Tribunus Militum
1,801
If the class objects are modeling the same underlying data structure, they should all be in the same model. If that isn't the case and you want to use child objects in an efficient way you can easily use references, which you are using in your above code sample (perhaps unknowingly). Python nearly always gives you reference semantics (where are you getting copy_of_alpha from, how do you know it's a copy)?

Code:
>>> bar = { 'Spam': 1 }
>>> class Foo:
...     def __init__(self, val):
...             self.val = val
... 
>>> f = Foo(bar)
>>> bar['Eggs'] = 2
>>> f.val
{'Eggs': 2, 'Spam': 1}

Depending on what you're trying to do, does it even make sense to keep the whole object tree in memory at the same time? If this was a typical web app you would probably have a data store. In that case you'd want to store a reference to the child via foreign key or DBRef or whatever and let the data layer figure it out.
 

Jonathon

Ars Legatus Legionis
17,645
Subscriptor
I'd probably do something like (assuming the "keys" to determining object equality are x and y in this case, and they're immutable):

Code:
class ReusableObject:
  def __init__(self, x, y): # constructor; not invoked directly by consuming code
    self.__x = x
    self.__y = y
  
  def get_x(): # not particularly pythonic, but the only way to guarantee that an attribute isn't writable
    return self.__x

  def get_y():
    return self.__y

class ReusableObjectFactory:
  def __init__(self):
    self._cached_objects = {}

  # call this to create instances of ReusableObject, not ReusableObject's constructor directly
  def make_reusable_object(self, x, y):
    if (x, y) in self._cached_objects:
      return self._cached_objects[(x, y)]
    else:
      newObject = ReusableObject(x, y)
      self._cached_objects[(x, y)] = newObject
      return newObject

Slots can be used to conserve a little more memory as well, if you need to (if you have a lot of ReusableObjects in ReusableObjectFactor's _cached_objects dict)-- it pre-declares the attributes to be used in a class (rather than adding attributes to an instance-specific dict). AFAICT (I might be missing something here, but I don't think I am), it's not a complete implementation of the flyweight pattern on its own, though (you'd still need to do something to reuse identical objects, if that's what you're trying to do).
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
[url=http:/civis/viewtopic.php?p=27271149#p27271149:3tdbcbp5 said:
kasperhooha[/url]":3tdbcbp5]Hi i dont know anything about programming but i want to learn what should i do first.??

Stop spamming random threads, start your own one (but first search for the other ones asking the same thing and indicate what you've failed to get/tried)

Also, read this before you do anything else
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
[url=http:/civis/viewtopic.php?p=27271727#p27271727:1l7ce6ay said:
kasperhooha[/url]":1l7ce6ay]I dont spam i just dont now shit// what programms should download or how to do programming i am really rokie and i just need help

Last time, *start your own thread*.
If you cannot work out how to do that there is no hope for you, give up.
Here's a link to help:
posting.php?mode=post&f=20

Any further posts like this will just be reported.
 
Status
Not open for further replies.