Using tuples in a function

I have a program that takes user input to update a table. As update can be made in three different areas of the program a function would be logical.

The input is a tuple and a string. I found no way to convert the tuple to a list inside the function. I got the program to work by converting the tuple to a list before calling the update function. Is there some basic language function I do not understand.

The most basic thing that does not work is converting a datetime variable to a string. x=str(date) give an error about not accepting an int value. No other way to convert datetime–>string worked either.

Unless I am missing something about your ask:

In [3]: tup = (1, 2, 3)

In [4]: list(tup)
Out[4]: [1, 2, 3]

There are lots of ways to convert datetimes to strings, but it all depends on the specifics of what format you need, so you would need to elaborate about your actual requirements.

Does time.strftime() do what you want?
See the python docs for details.

In order to understand the issue with the code, it would be useful to see the relevant code. Here is some good advice about preparing code to demonstrate a problem to others:

tuple

As I tried to say in the code moving the list1 assignment statements makes these statements not work.

What is update_rec? Where does it come from, what parameters does it expect? What is the actual (full) traceback that you are seeing? There is not enough information here to speculate.

Also: please never post pictures-of-code, as they are not accessible to anyone using a screen readers or other assistive devices, and also cannot be easily copy-pasted by anyone trying to help. Instead always copy and past code as actual text in formatted code blocks.

1 Like

First I really appreciate everyone’s help. I posted the question the way I did because I was sure the answer was going to be you have to do “this” inside a function. The image got posted because I can not figure out how to do the code tags so I tried to post html. that got me your choices were jpg/png among other things. update_rec is a function I wrote. If I can not figure out anything else I will post a link to the entire program, as there is nothing private involved in the code. Thanks again

@dtd here is a guide regarding code fomatting:

Discourse Guide: Code Formatting - Meta - Stonehearth Discourse

Generally speaking type three backticks ``` on a line by themselves, then paste your code below. and then another line with three backticks ``` below the code.

You can also do it by selecting the code and then clicking </>.

Please read the pinned thread in order to understand this. Also, as general advice: you should make sure to use a monospace (“typewriter”) font in the program that you use to edit your code, and indent the code with spaces, not tabs. In the long run, this will make it much easier to read the code (which is very important, because you will spend much more time reading your own code than you spend writing it). It will also make it easier for you to “shift” visually between your code editor and a terminal window (and please don’t think “I’ll just make the terminal window use a ‘normal’ font”; if your OS even gives you the option, it will make Python’s error messages look wrong - they’re specially designed to use that typewriter formatting).

Anyway, there is still not enough information here to understand the problem. You tell us “I found no way to convert the tuple to a list inside the function”, but we can’t know which function is “the function” from this. I guess, from the code that you showed, that you are talking about trying to call update_rec. However, we cannot guess what this function does, therefore we cannot guess what is valid to pass to it when calling it, therefore we cannot guess how to transform the list1 and list2 that you have into an acceptable call to the function. (We cannot even know that it makes any sense at all to try.) The variable names in the program also do not give us a hint: when something is called list1 or list2, that does not help us understand the purpose of that variable. From the rest of the code, I get the basic idea that you are trying to query a database using MySQLdb, and then create some data that you will use to update_rec something. I guess this means to use someone else’s function that will update a record in the database. But I can’t know that, and I can’t know how it will be updated, and I can’t know what should be provided to the function, and I can’t know the rules that the function will use to understand what was provided. I also can’t know what went wrong when you tried the code, because you did not show us.

Discourse Guide: Code Formatting - Meta - Stonehearth Discourse

Generally speaking type three backticks on a line by themselves, then paste your code below. and then another line with three backticks below the code.
Matthew Barnett
MRAB
1d

You can also do it by selecting the code and then clicking </>.
Karl Knechtel
kknechtel
1d

The image got posted because I can not figure out how to do the code tags

Please read the pinned thread in order to understand this. Also, as general advice: you should make sure to use a monospace (“typewriter”) font in the program that you use to edit your code, and indent the code with spaces, not tabs. In the long run, this will make it much easier to read the code (which is very important, because you will spend much more time reading your own code than you spend writing it). It will also make it easier for you to “shift” visually between your code editor and a terminal window (and please don’t think “I’ll just make the terminal window use a ‘normal’ font”; if your OS even gives you the option, it will make Python’s error messages look wrong - they’re specially designed to use that typewriter formatting).

Anyway, there is still not enough information here to understand the problem. You tell us “I found no way to convert the tuple to a list inside the function”, but we can’t know which function is “the function” from this. I guess, from the code that you showed, that you are talking about trying to call update_rec. However, we cannot guess what this function does, therefore we cannot guess what is valid to pass to it when calling it, therefore we cannot guess how to transform the list1 and list2 that you have into an acceptable call to the function. (We cannot even know that it makes any sense at all to try.) The variable names in the program also do not give us a hint: when something is called list1 or list2, that does not help us understand the purpose of that variable. From the rest of the code, I get the basic idea that you are trying to query a database using MySQLdb, and then create some data that you will use to update_rec something.

#!/usr/local/bin/python

""" Update the newtrx table using previous entries. This replaces doing this
    by hand using Libre Office. Values changed are Description, Comment, and
    code. The reply is three values, comma separated."=" means no change
    
    call truistupdt.py table

"""
import sys
import os
import re
import datetime as dt
import MySQLdb
from warnings import filterwarnings

fields=['acct','Date','Number','Description','Amount','Comment','Code','PF','id']

os.system('clear')                #clear the window
db = MySQLdb.connect('localhost','toot','rudy-toot','dbx')
filterwarnings('ignore','.*')
c=db.cursor()

def update_rec(c,orec):
  #print(dlist)
  for i in range(len(orec)):
    if type(orec[i])=='str':
      orec[i]='"'+orec[i]+'"'
    else:
      orec[i]='"'+str(orec[i])+'"'
    
  x=','.join(orec)+');'
  insertStmt='insert into t values ('+x
  #print(insertStmt)

  insertStmt='insert into tmptrx values ('+x
  #print(insertStmt)
  
  try:
    c.execute(insertStmt)
    c.execute('commit')
    updated=True
    
  except Exception as e:
    print(repr(e))
    print('error',insertStmt)
    sys.exit(4)

  return updated
 
if len(sys.argv)!=2:
  print('usage: truistupdt.py table')
  sys.exit(4)
  
# add modified records to tmptrx. The "real" table is updated after
# all records have been updated in tmptrx
tbl=sys.argv[1]
c.execute('drop table if exists tmptrx;')
c.execute('create table tmptrx like '+tbl+';')
c.execute('explain '+tbl+';')      #add key to the output table if necessary
zitems=c.fetchall()
if len(zitems)==8:
  c.execute('alter table tmptrx add id int(11) auto_increment, add primary key(id);')
  c.execute('alter table '+tbl+' add id int(11) auto_increment, add primary key(id);')

cmd="select * from "+tbl+" where code=99 or Description='check';"
c.execute(cmd)
zitems=c.fetchall()
for row in zitems:
  if row == None: break
  list1=[*row,]
  cdate=str(row[1])
  updated=False
  r=dict(list(zip(fields,row)))
  desc=r['Description'].strip()
  desc=desc.replace('*','')
  if desc!='Check' and code!=99:
    continue
  
  print('Update '+str(r['Number'])+' '+r['Description'])  
  zchecks=''
  while len(zchecks)==0:
    ans=input('Enter Description: ')
    if ans=='okay': break
    cmd='select * from truistmap where Description regexp "'+ans+'";'
    c.execute(cmd)
    zchecks=c.fetchall()
    for item in zchecks:
      print(item)
    dtd=43
    if len(zchecks)==0:
      list2=list(ans.split(','))
      list1[1]=cdate
      list1[3]=list2[0]
      if len(list2)==1: break
      updated=update_rec(c,list1)
    break

  if updated: continue
  ans=input('Enter values for check '+str(r['Number'])+'\n')
  val=ans.split(',')
  rec=list(row)
  if val[0]!='=':             # Convert the tuple to a list and
    rec[3]=val[0]             # update it with the values entered
  if val[1]!='=':
    rec[5]=val[1]
  if val[2]!='=':
    rec[6]=val[2]
  dtd=42
  list2=list(ans.split(','))
  list1[1]=cdate
  list1[3]=list2[0]
  list1[5]=list2[1]
  updated=update_rec(c,list1)           # update the current row
  print('-------------------')

dtd=42  
db.close()
sys.exit(0)  

The full program