Renaming functions and vars
Alex Martelli
aleaxit at yahoo.com
Tue Apr 3 11:58:44 EDT 2001
"Mikkel Rasmussen" <footech at get2net.dk> wrote in message
news:oFly6.191$PR2.21530 at news.get2net.dk...
> Is there a smart or automatic way to rename functions and variables?
>
> I would like to prepend a string to the function names in a module. It
> shouldn't be too difficult to program it, but I would like to spare myself
> the effort.
>
> And how about variables? I would like to define different prefixes to
> variable names. The renaming should not change the semantics of the
program,
> so I can't just use copy-paste here.
It's not clear to me whether you want to write a source-to-source
converter, or something that works on a module-object that has
already been loaded into memory...? Either is easy (for functions;
'variables' may be a very different issue depending on whether
you mean module-global ones, or function-local ones) but the
approaches are quite different.
For an already-loaded module object, you can take advantage of
the fact that Python has already parsed it for you. E.g.:
def prefixFunctions(module, prefix):
names_and_values = module.__dict__.items()
for name, value in names_and_values:
if callable(value) and not name.startswith(prefix):
newname = prefix + name
if hasattr(module, newname):
# whatever you want to do in such a conflict case!
pass
else:
delattr(module, name)
setattr(module, newname, value)
You'll probably want to tweak this (I'm assuming you don't
want to double-up on existing prefixes, that you want to
rename all callables and not just functions, etc), but still
it should be a reasonable basis for you to start from. Note,
however, that this will not handle references _to_ functions
in this module by their old, not-existing-any-more names --
see below.
For a source-to-source transformation, on the other hand,
you may choose to operate at different levels (plain
text + re's, standard module tokenize, etc, etc).
It's anything but trivial, at least potentially, because
you have to correctly identify all _uses_ of functions
of your module within the module itself -- and those may
happen in many guises; and renaming just functions (and
not, e.g., arguments) affects that:
def bar(xxxfoo):
return 23
def foo(xxxbar):
return bar(xxxbar)
Now if I try to rename all functions in this module by
prepending a prefix 'xxx' I get (at best!):
def xxxbar(xxxfoo):
return 23
def xxxfoo(xxxbar):
return xxxbar(xxxbar)
but it won't work because _argument_ xxxbar hides
_function_ xxxbar (nee bar) from within function
xxxfoo (nee foo). Again, diagnosing potential
name conflicts seems hard.
Alex
More information about the Python-list
mailing list