this post was submitted on 20 Sep 2023
10 points (100.0% liked)

Python

6343 readers
3 users here now

Welcome to the Python community on the programming.dev Lemmy instance!

πŸ“… Events

PastNovember 2023

October 2023

July 2023

August 2023

September 2023

🐍 Python project:
πŸ’“ Python Community:
✨ Python Ecosystem:
🌌 Fediverse
Communities
Projects
Feeds

founded 1 year ago
MODERATORS
 

Constant modules are modules that often contains variables that you want to use in many places without relying on hard coded values. Sometime you store paths (often relatives).

Is it a good thing to use pathlib.Path() object is modules dedicated to constant?

Or is there anything that you should know before choosing to do so?

I would say the same question appears for using re.compile() in constants.

Any advise?

top 8 comments
sorted by: hot top controversial new old
[–] qwop@programming.dev 5 points 1 year ago

Sounds fine, they're both immutable which helps.

[–] vrt3@feddit.nl 3 points 1 year ago

I do that all the time.

[–] gigachad@feddit.de 2 points 1 year ago* (last edited 1 year ago)

I don't see why not. However I like to have my constants module contain data structures as simple as possible, therefore I would prefer strings (which are also immutable), and create a Path object when I need it. I can see though that you usually won't have the case where you would not want the path to be a Path object.

[–] danielquinn@lemmy.ca 2 points 1 year ago (2 children)

If it's a path, you should use Path. If it's a regular expression, define it as such with re.compile(). If the purpose of such a module is to reduce boilerplate, then defining these values as strings only necessitates boilerplate later on to convert them.

There's one edge case to consider, though it's very "edge". If you define a very long/complex regex as a constant and then import from that file, Python will run .compile() on import. If you're not actually using that regex though (say you imported the file to use a different value) then you're burning CPU there for no reason.

I generally don't recommend that you concern yourself with that sort of thing though until you run into real performance problems. Most regexes you compile take no time at all, and the benefit of storing everything as the object you'd expect has big benefits for developer cognitive load.

[–] Narann@lemmy.world 2 points 1 year ago

Thanks a lot for the detailed answer.

@danielquinn agreed! You can work around the performance issues by wrapping it in a function.

[–] Fal@yiffit.net 0 points 1 year ago (1 children)
[–] Narann@lemmy.world 1 points 1 year ago

That was my question. :)