0

I have been working with large data sets on some open source software I've been working on (wxStocks on github). I am analyzing stocks, and since all stocks are loaded into active memory when the program starts, I see no reason to use a database structure.

However, it's been challenging to organize the files due to my need to use a global variable list that holds all the stocks so I can easily return a stock via it's ticker string.

I have come up with a solution via the garbage collector:

def return_stock_from_active_memory(ticker):
    ticker = ticker.upper()
    for obj in gc.get_objects():
        if type(obj) is Stock:
            if obj.symbol == ticker:
                return obj

I have been informed from more experienced python programmers that I am playing with fire by even importing the garbage collector in the first place, and that it is considered extremely bad form, still, this and another function I've written that returns all stock objects are extremely useful.

Is the function above an acceptable way to find an object in active memory via a unique attribute string? If not, how should I go about finding objects while moving between different files without creating an infinite loop importing variables into each respective file.

Jonathan Drapeau
  • 2,610
  • 2
  • 26
  • 32
Matt
  • 11
  • 2
  • 1
    Why not maintain a map of `Stock` objects keyed by their symbol when you create each `Stock` instance? – univerio Aug 26 '14 at 21:20
  • I'm not exactly sure how to do that (only been programming for casually for about two years). I'll try and look up. – Matt Aug 26 '14 at 21:22
  • Wouldn't that involve a local variable anyway? I'm really trying to return objects without having to deal with any local or global variables. – Matt Aug 26 '14 at 22:09
  • It would involve a global variable, but that's the cleanest way to do it. Why are you opposed to using global variables? – univerio Aug 26 '14 at 22:22
  • 1
    Because if i move my utility functions to a seperate file, then importing global variables becomes tricky as it seems to cause infinite import loops. I think i will probably just use the dbm module with a seperate file rather than loading everything in active memory at startup. – Matt Aug 26 '14 at 22:26
  • You just have to make sure to put your global `Stock` map in a separate module that imports nothing else from your other modules. – univerio Aug 26 '14 at 23:31
  • Why don't you use a simple no-sql db, with keys/values pairs? – dfranca Aug 28 '14 at 12:30
  • `Lib/inspect.py` provides tools for inspecting live objects. https://docs.python.org/2/library/inspect.html – ben rudgers Aug 28 '14 at 12:46

0 Answers0