There are cases that you dont want Python interpreter to write bytecode. For example, you are too lazy to use some format for configuration file. Instead, you use Python code as the configuration. Generally, it will be fine, just little annoying when there is bytecode written alongside the configuration file.

If you dont like, you can turn it off. There are two ways to do so:

  1. Running Python interpreter with -B option or
  2. Setting sys.dont_write_bytecode to True.

These two options only work for Python 2.6+, it also work in Python 3, no bytecode will be written in __pycache__ directory.

Here is a demostration script:

import glob
import imp
import sys

sys.path.append('/tmp')

print('sys.dont_write_bytecode = %s' % sys.dont_write_bytecode)
print('')

# module testimport
with open('/tmp/testimport.py', 'w') as f:
  pass
print('importing /tmp/testimport.py')
import testimport
print(testimport)
print('')

sys.dont_write_bytecode = True
print('sys.dont_write_bytecode = %s' % sys.dont_write_bytecode)
print('')

# module testimport2
with open('/tmp/testimport2.py', 'w') as f:
  pass
print('importing /tmp/testimport2.py')
import testimport2
print(testimport2)
print('')

# module prog.conf
with open('/tmp/prog.conf', 'w') as f:
  pass
print('importing /tmp/prog.conf')
conf = imp.load_source('prog_conf', '/tmp/prog.conf')
print(conf)
print('')

print('/tmp/*c: %s' % glob.glob('/tmp/*c')) #**/
sys.dont_write_bytecode = False

importing /tmp/testimport.py
<module 'testimport' from '/tmp/testimport.py'>

sys.dont_write_bytecode = True

importing /tmp/testimport2.py
<module 'testimport2' from '/tmp/testimport2.py'>

importing /tmp/prog.conf
<module 'prog_conf' from '/tmp/prog.conf'>

/tmp/*c: ['/tmp/testimport.pyc']

Only module testimports bytecode is written. The setting dont_write_bytecode affects any importing function as you can see imp.load_source does not result a bytecode /tmp/prog.confc written.