How to extend a tuple of tuples?

Chris Angelico rosuav at gmail.com
Fri Sep 9 08:28:01 EDT 2016


On Fri, Sep 9, 2016 at 10:21 PM, Frank Millman <frank at chagford.com> wrote:
> I am building a series of JOINs for a SQL statement. Some of them can be
> nested - table A is joined from table B is joined from table C. In other
> parts of the same SQL statement, table A could be joined from table D which
> is joined from table E.
>
> For each potential candidate, I need to check if I have already built the
> JOIN. If so, just use it. If not, build it, and update a dictionary to
> indicate that it has been built.
>
> The key to the dictionary is the path to the joined table, which could be
> several levels deep. I build up a tuple to represent the path. Each table
> needs two pieces of information to identify it, so I use a tuple for each
> identifier.
>
> The value portion of the dictionary is simply the alias generated for the
> joined table. I use the alias in the body of the SQL statement.

Sounds fair enough. A tuple is a pretty reasonable way to do this.

The other approach would be to craft the aliases directly, as strings.
For instance, your first example could be JOIN_A_B_C, and your second
JOIN_A_D_E. (Sort the table names alphabetically before "_".join()ing
them if you want order to be insignificant.) Obviously this won't do
if it runs the risk of crashing into length limits in your SQL engine,
but if you find tuples too annoying, this is an equally valid way of
crafting the keys for your dictionary.

Overall, this sounds like one of those horrendously messy pieces of
code that exists because... it's dealing with a horrendously messy
situation. Which, sad to say, happens all too often in real-world
code, much as we'd love to pretend it doesn't in examples on mailing
lists :|

ChrisA



More information about the Python-list mailing list