[Tutor] Proper SQLite cursor handling?
dn
PyTutor at DancesWithMice.info
Sat Jul 3 05:02:54 EDT 2021
On 03/07/2021 15.55, boB Stepp wrote:
> I have the start of a class to create solitaire game objects:
>
> class SolitaireGame:
> """Representation of a solitaire game."""
>
> def __init__(self, db_cursor: sqlite3.Cursor, game_name: str) -> None:
> """Create or open a solitaire game."""
> self.cur = db_cursor
> self.game_name = game_name
>
> My current thought is to create only a single cursor object and use it
> throughout the program's lifetime. Is this a sensible thing to do?
> In the above class skeleton my intent is to retrieve the game
> information from the database using the passed in cursor. During the
> course of a program session the user may have any number of different
> solitaire games open, so each of these game objects would have its own
> reference to the _same_ cursor object. I have an uneasy feeling that
> this might cause issues, but I don't know enough (yet) and am still at
> the pondering point for this class. Eventually I will write tests and
> try things out to see what happens, but one of you might save me some
> painful explorations and time!
Plenty of DB advice, elsewhere.
As a general rule, it is a good idea to keep I/O separate from
'processing'. Given that you are learning DB interactions, probably even
more advantageous.
Why? You can learn, develop, and test each phase independently, ie
- you can develop the DB routines quite separately
- you can develop the game class using manually-prepared data that won't
need to come from a DB, nor return to one
...and after all that, when you're ready:
- you can switch between file-stores/DBMS-es whenever the whim takes you
(without affecting the mechanics of the game)
In other words, try something like:
class SolitaireGame:
"""Representation of a solitaire game."""
def __init__(self, game_parameters ) -> None:
"""Create or open a solitaire game."""
self.name = game_parameters.name or retrieval function or ...
etc
now, to run a game, the three steps are self-documenting:
game_parameters = get_game_data_from_DB( db_defns )
game = SolitaireGame( game_name, other_game_data )
store_game_results_in_DB( game.results_for_DB() )
NB the DB interaction(s) has been illustrated as two functions, for ease
of comprehension. I'd argue that a class (with two I/O methods) would be
a better choice, because its namespace maintains "state". See (object)
illustration within __init__().
--
--
Regards,
=dn
More information about the Tutor
mailing list