interpret (string) NULLs as empty strings, not None

2,231 views
Skip to first unread message

Catherine Devlin

unread,
Aug 6, 2009, 3:08:34 PM8/6/09
to sqlal...@googlegroups.com
When populating objects through the ORM, I'd like to interpret all
NULL values fetched from VARCHAR2 / NVARCHAR2 columns in the database
as empty strings ('') instead of `None`s.

Is there any way to set that behavior globally? Failing that, how
would you recommend doing it?

(I'm using Oracle, which does not distinguish between empty strings
and NULLs; but, once my data is on the Python side, I do a zillion
string operations on it and don't want to bother checking for `None`s
every time I slice, check `in`, etc. When I send data back to Oracle,
any empty strings I send will be converted back to NULLs as Oracle
saves them, anyway.)

Thanks!
--
- Catherine
http://catherinedevlin.blogspot.com/
*** PyOhio * July 25-26, 2009 * pyohio.org ***

Michael Bayer

unread,
Aug 6, 2009, 3:14:17 PM8/6/09
to sqlal...@googlegroups.com
Catherine Devlin wrote:
>
> When populating objects through the ORM, I'd like to interpret all
> NULL values fetched from VARCHAR2 / NVARCHAR2 columns in the database
> as empty strings ('') instead of `None`s.
>
> Is there any way to set that behavior globally? Failing that, how
> would you recommend doing it?


use a TypeDecorator that creates that behavior. To get a "global" effect,
perhaps in your imports make sure that your custom type overrides the
usage of String/Unicode in your Table definitions.

Catherine Devlin

unread,
Aug 21, 2009, 10:32:56 AM8/21/09
to sqlal...@googlegroups.com
On Thu, Aug 6, 2009 at 3:14 PM, Michael Bayer<mik...@zzzcomputing.com> wrote:

>> When populating objects through the ORM, I'd like to interpret all
>> NULL values fetched from VARCHAR2 / NVARCHAR2 columns in the database
>> as empty strings ('') instead of `None`s.
>

> use a TypeDecorator that creates that behavior.

Belated but huge thanks for this. This is a much simpler solution
than I had hoped for.

class NullCatchingString(types.TypeDecorator):
# NULL results are returned as empty strings.
impl = types.String
def process_result_value(self, value, engine):
if value:
return value
else:
return ''

> To get a "global" effect,
> perhaps in your imports make sure that your custom type overrides the
> usage of String/Unicode in your Table definitions.

In this case, my tables are autoload=True, so I don't think overriding
String will help. However, I realized that I've got a limited number
of columns that need this behavior, and explicitly defining those
columns isn't too much of a pain after all.

tbl = Table('mytable', metadata,
Column('suchandsuch', NullCatchingString),
autoload=True, autoload_with=engine)

Thanks again!

Reply all
Reply to author
Forward
0 new messages