[Tutor] Declaring variables

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Apr 7 17:51:05 EDT 2016


On 07/04/2016 18:49, Dimitar Ivanov wrote:
> Hello everyone,
>
> I have a (hopefully) quick and easy to explain question. I'm currently
> using MySQLdb module to retrieve some information from a database. In my
> case, the result that's being yield back is a single line.
>
> As far as my understanding goes, MySQLdb function called 'fetchone()'
> returns the result as a tuple. Problem is, the tuple has some unnecessary
> characters, such as an additional comma being returned. In my case:
>
>>>>   idquery = 'select id from table;'
>>>>   cur = mysql.cursor()
>>>>   cur.execute(idquery)
>>>>   id = cur.fetchone()

Note that using 'id' is frowned upon as you're overriding the builtin of 
the same name.  I'll use id_ below.

>>>>   print id
> ('idinhere',)

No, it isn't an additional comma, it's a tuple that only has one field.

>
> I stumbled across an example given like this:
>
>>>>   (id,) = cur.fetchone()
>
> So I decided to give it a try and the result is exactly what I need:
>
>>>>   (id,) = cur.fetchone()
>>>>   print id
> idinhere
>
> My question is - can I reliably use this method? Is it always going to
> return the string between the brackets as long as I define the variable
> with '(,)'? I'm planning to use another query that will be using the result
> from this one and then update another database with this result but I must
> be sure that the variable will always be the string in and between the
> brackets otherwise I'm risking to mess up a lot of things big time.

I'd write it as:-

id_ = cur.fetchone()[0]

>
> A backup plan I had was to use the following:
>
>>>>   id = cur.fetchone()
>>>>   for x in id:
>>>>     id = x

Yuck :)

>
> But if the method above is certain to always return only the value I need,
> I find it to be a far more elegant solution.
>
> Also, just to clarify things for myself - what does this method of
> declaring variables do exactly? I'm sorry if this isn't the right place the
> ask and if this has been documented clearly already, I'm not sure what to
> use as a search term in order to find an answer.

In Python nothing is declared as in C or Java. A name is bound to an 
object.  So from the above the name 'id_' is bound to the string object 
that happens to be 'idinhere'.  Once this has been done there is nothing 
to stop you from writing:-

id_ = 1
id_ = 1.0
id_ = Point(1, 2)
id_ = Complicated(lots, of, parameters, here)

>
> Thanks a lot in advance! I hope I posted all the details needed and my
> question is easy to comprehend.

The only things that are sometimes needed are your OS and Python 
version.  The latter can be deduced from your 'print id' rather than 
'print(id)', indicating that it is 2.x, not 3.y.

>
> Regards,
> Dimitar
>


-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list