My preferred method is to actually fix the library rather than playing with environment variables that may or may not actually be in scope depending on how the application is run. This is actually a fairly simple process.
First, look at the error output to see where the offending python module is located:
ImportError: dlopen(/Library/Python/2.7/site-packages/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib Referenced from: /Library/Python/2.7/site-packages/_mysql.so Reason: image not found
Okay, so the offending file is /Library/Python/2.7/site-packages/_mysql.so
Next, figure out where _mysql.so thinks it should find libmysqlclient.18.dylib:
% otool -L /Library/Python/2.7/site-packages/_mysql.so
/Library/Python/2.7/site-packages/_mysql.so:
libmysqlclient.18.dylib (compatibility version 18.0.0, current version 18.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 169.3.0)
So, it‘s looking for libmysqlclient.18.dylib with no path information, let‘s fix that:
% sudo install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib /Library/Python/2.7/site-packages/_mysql.so
Now _mysql.so knows the full path to the library and everything works, regardless of environment variables.
% otool -L /Library/Python/2.7/site-packages/_mysql.so
/Library/Python/2.7/site-packages/_mysql.so:
/usr/local/mysql/lib/libmysqlclient.18.dylib (compatibility version 18.0.0, current version 18.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 169.3.0)