Getting Rid of Redundant Import In SConscripts

This is the seventh post in my SCons series. The topic of this post is getting rid of the last bit of overhead in SConscript files – the Import('*') line.

According the the SCons user guide, a SConscript files needs to Import('...') shared symbols. It’s possible to import all exported symbols with Import('*'). This is the method I used in previous episodes to make shortcuts available in module-level SConscript files

Perhaps you’re fine with this little remaining overhead in every SConscript file. After all, it’s not such a big deal. With the wildcard syntax, you will never need to go over old SConscript files and update their import list when you add a new shortcut.

If you prefer your SConscript files as minimal as possible, here’s a dirty little hack I use. Instead of passing the shortcuts dictionary to a delegated SConscript file using the exports argument, I modify the _SConscript.GlobalDictdirectly before invoking the SConscript() function.

Using my example project, you may recall from the previous episode how the delegation looks like:

def process_module(self, module):
    print 'scons: |- Reading module', module, '...'
    # Execute the SConscript file, with variant_dir set to the
    #  module dir under the project flavored build dir.
    self._env.SConscript(
        sconscript_path,
        variant_dir=os.path.join(self._env['BUILDROOT'], module),
        exports=shortcuts)

The hack is a minor modification of this snippet:

def process_module(self, module):
    print 'scons: |- Reading module', module, '...'
    # Execute the SConscript file, with variant_dir set to the
    #  module dir under the project flavored build dir.
    SCons.Script._SConscript.GlobalDict.update(shortcuts)
    self._env.SConscript(
        sconscript_path,
        variant_dir=os.path.join(self._env['BUILDROOT'], module))

The result of the hack is that the shortcuts are injected directly into the global dictionary. This means that these symbols are available in SConscript files, without any call to Import(..)!

As always, the entire project is available on my GitHub scons-series repository. Feel free to use / fork / modify. If you do, I’d appreciate it if you share back improvements.

See the scons tag for more in my SCons series.

Warning: Unlike other SCons extensions I describe, I refer to this one as a “hack”. The reason is that I access a protected member of another namespace, using an undocumented feature of SCons. This means that I cannot assume this will work with future versions of SCons, as private & protected areas are subject to change without notice. If you choose to use this hack, make sure you fully understand the potential consequences!

No Comments Yet.

Leave a Reply