How to avoid hash (#) char in python?

I am using pyodbc to query AS400 (unfortunately), and some column names have hashes in them! Here is a small example:

self.cursor.execute('select LPPLNM, LPPDR# from BSYDTAD.LADWJLFU')

for row in self.cursor:
    p = Patient()
    p.last = row.LPPLNM
        p.pcp = row.LPPDR#

I get errors like this:

 AttributeError: 'pyodbc.Row' object has no attribute 'LPPDR'

Is there any way to avoid this? It seems doubtful that the hash is even allowed in the var name. I just took python today, so forgive me if the answer is well known.

Thanks Pete

+3
source share
4 answers

Use function getattr

p.pcp = getattr(row, "LPPDR#")

This is, in general, the way you deal with attributes that are not legal Python identifiers. For example, you can say

setattr(p, "&)(@#$@!!~%&", "Hello World!")
print getattr(p, "&)(@#$@!!~%&")  # prints "Hello World!"

Also, as JG suggests, you can give your columns an alias, for example by saying

SELECT LPPDR# AS LPPDR ...
+7

, :

 self.cursor.execute('select LPPLNM, LPPDR# as LPPDR from BSYDTAD.LADWJLFU')
+5

self.cursor.execute , :

for row in self.cursor:
        p = Patient()
        p.last = row[0]
        p.pcp = row[1]

: -)

+2

The answer was given, but this is another alternative (based on the answer of Adam Bernier + unpacking), which I consider the cleanest:

for row in self.cursor:
    p = Patient()
    p.last, p.pcp = row
+1
source

Source: https://habr.com/ru/post/1713001/


All Articles