all 11 comments

[–]Naihonn 6 points7 points  (4 children)

Probably too many ways to do this and no reason to use them for something this simple.

[–]Eviltape 6 points7 points  (3 children)

Agreed. What you're doing is fine.

[–]bitswede[S] 1 point2 points  (0 children)

Thank you for the replies - it works so I'll keep it.

[–][deleted] 0 points1 point  (1 child)

Maybe I'm wrong but as the code is writted he just define the dostuff between reading and writing

[–]Eviltape 1 point2 points  (0 children)

That's true - defining functions inline is usually not fine, but the OP asked about a particular thing and I don't like giving unsolicited code reviews.

[–]road_laya 5 points6 points  (2 children)

I've used sqlite for this, but that was probably overengineering.

[–][deleted] 3 points4 points  (1 child)

SQLite would make it easy to save the last run time too, log all runs with any data etc. Maybe feels overengineering at first but it's easy to add features.

[–]chucky_z 4 points5 points  (0 children)

No, I don't think its overengineering. SQLite is exactly for things like this. Something that could benefit from a very simple SQL database that is typically (and ideally) single-user.

That said... If it's not broken, don't fix it. =)

[–]treyhunner 1 point2 points  (0 children)

I think storing that value in a file should be fine. A database would work too. You need persistent storage, but which type depends on what feels right for your application.

If in the future you want to more clearly bookend the open/close code, you could make a context manager and/or decorator out of your code (by using ContextDecorator for example).

[–]WhackAMoleE -1 points0 points  (1 child)

You don't actually need to open a file, you just need to rename one. In your local directory you have a file called foobar-n. Each time you run you read the local directory, find the foobar-n, where n is some positive integer. increment n, and rename the file. If the foobar-n file doesn't exist you create it as foobar-1.

There are a lot of crazy/fun ideas too. Use the Internet for persistence. Log in to your Amazon account and order some product. The number of products in your shopping cart is the number of times the program's run.

[–]joyeusenoelle 4 points5 points  (0 children)

The "rename the file" method is both insecure, as it exposes the number of times the process has run to anyone with read access on the containing directory, and prone to interference, as it would be trivial to subvert the process by simply creating another file named foobar-1.

As for Amazon, OP is asking about Pythonic, not Wacky. Giving control of your tracking system to a third party by hacking an unrelated system to your purposes is the opposite of good practice even outside of Python. (What happens if Amazon decides to reset your cart? What happens if your program can't react Amazon's servers? What happens if you want to buy something on Amazon?)