Reputation: 21238
In all of my Python module files I put the module version with __version__
.
Now if I release my Python library, I want to increase this module version inside all Python module files automatically.
I know that I can access the version of a module for reading like this:
mymodule.py:
# my module
__version__ = "0.0.1"
usesmymodule.py:
import mymodule
# Gives me "0.0.1"
print mymodule.__version__
Now how can I save the module source file after I changed its version? In a way like this:
mymodule.__version__ = "0.0.2"
mymodule.__save__() # does not exist as such, but thats what I want
I could of course apply an sed-like mechanism, reading the source file line by line and replace the __version__
- I already have a Bash-script doing that. But I want to replace that Bash-script and increase the module versions in a more Pythonic way. Do you know of any?
Upvotes: 2
Views: 704
Reputation: 21238
I agree to the answers of Thomas and Ignacio - especially that I should have that version number only in one central place. But for modules where that is not an option (or in my case - being to lazy), I now wrote myself an alternative to using Bash/sed. It works really well and can be integrated into a bigger Python build-script:
import fileinput
def replace_version(filename, version):
'''Replace version in file with new version'''
for line in fileinput.FileInput(filename,inplace=1):
if line.startswith('__version__'):
print('__version__ = \'%s\'' % version)
else:
sys.stdout.write(line)
replace_version('mymodule.py', '0.0.2')
Upvotes: 1
Reputation: 40340
There's not really a neat way to change a variable and update the source code. After the program has run, you don't know if the variable came from a simple assignment, a function call, something inside an if statement, etc. There are some ways to parse the code without running it, edit the AST, and write it back out, but it's complex and inconvenient.
Three practical solutions:
__version__
in every module - just in the top level of the library.__version__
in one place and refer to it everywhere else, e.g. from .versionno import __version__
.Upvotes: 3
Reputation: 798686
Oddly enough, using sed for this could almost be considered Pythonic, since it is absolutely the correct tool for the job.
Upvotes: 3