Git Automation
Some of you may have read my Git Battles post, where I talked about how I developed and a documented a Git workflow.
这篇文章谈的是如何在代码中使用常量:为什么重要、有什么好处、怎样才能用得好。遗憾的是,我是吃了苦头才学会的。最初,我在代码里并没有使用多少常量。
我不怎么重视常量。和许多项目一样,我大量使用“魔法字符串”。写起来又快又方便,到处都是。
form_data = {
"name": "Update Operation",
"to_module": "DeplMgr",
"to_method": "post_job","
"op": "update",
"element_type": "monerod_remote",
"element": self.monerod,
}
所谓魔法字符串,就是直接硬编码在应用源代码里,并对程序行为或逻辑有重要影响的字符串字面量。“魔法”意味着阅读代码的人不一定立刻明白它的用途或含义,因为它的重要性没有被明确命名或说明。
第一步是统一常量命名。我已经连续重构约八个小时,开始为常量该怎么命名而头疼。盯着屏幕、起了一堆糟糕名字、低声抱怨了一阵后,我终于做了从一开始就应该做的事:查资料。
常量采用一致的命名标准非常重要。我使用下面这套规范,效果很好。常量分为三类:
| 类型 | 示例名称 | 示例值 |
|---|---|---|
| 字段 | P2POOL_VER_FIELD | p2pool_ver |
| 标签 | P2POOL_VER_LABEL | “P2Pool version” |
| 默认值 | P2POOL_VER_DEFAULT | “4.10.1” |
最终,我意识到魔法字符串确实是个坏东西,于是迎来了清算日:整整一天再加六小时,总计 30 小时的重构马拉松。目标很简单:清除魔法字符串,全部替换为常量。过程非常艰苦。
快结束时,我的手腕开始疼,甚至担心自己是不是要患上腕管综合征。后来才发现是因为常量都是大写字母,我一直不停按 Shift 键。改用 Caps Lock 之后,情况好多了。
form_data = {
NAME_FIELD: UPDATE_OPERATION_LABEL,
TO_MODULE_FIELD: DEPLOYMENT_MGR_DEFAULT,
TO_METHOD_FIELD: POST_JOB_FIELD,
OP_FIELD: UPDATE_FIELD,
ELEMENT_TYPE_FIELD: MONEROD_REMOTE_FIELD,
ELEMENT_FIELD: self.monerod,
}
错误可能悄悄混进来,产生难以追踪的副作用。比如这里写 p2pool_ver,另一个地方却写 p2pool_version。程序不会报运行时错误,只会以奇怪的方式失败。
我用 Visual Studio Code 作为 IDE,它有语法高亮。使用魔法字符串时,你根本没有充分发挥 VS Code 的优势。
时间过去了。我慢慢意识到,把常量堆成一大堆不是终点。它们散落各处,很难查找,应用代码里依然到处直接引用,感觉并不整洁。我不过是把魔法字符串换成了魔法常量。
虽然有进步,但……
于是我开始另一次重构。这次不是为了消灭魔法字符串,而是把常量组织成有逻辑的分组。想法很简单:常量应该归属于自己的领域,应用代码几乎不应直接接触底层常量定义。
我使用下面的 ConstGroup.py。它允许在常量文件中指定数据类型,同时保持代码整洁易读。
class MetaConst(type):
"""Metaclass that collects public attributes into a dictionary-like mapping."""
def __new__(mcs, name, bases, namespace):
cls = super().__new__(mcs, name, bases, namespace)
cls._constants = {
k: v for k, v in namespace.items()
if not k.startswith("_") and not callable(v)
}
return cls
def __getitem__(cls, key):
return cls._constants[key]
def keys(cls):
return cls._constants.keys()
def values(cls):
return cls._constants.values()
def items(cls):
return cls._constants.items()
def __iter__(cls):
return iter(cls._constants)
def __contains__(cls, item):
return item in cls._constants
def __repr__(cls):
return f"<ConstGroup {cls.__name__}: {cls._constants!r}>"
class ConstGroup(metaclass=MetaConst):
"""Base class for constant groups (dict + namespace)."""
pass
以下是我目前使用的常量文件中的一些片段:
from db4e.Modules.ConstGroup import ConstGroup
class DField(ConstGroup):
COLORTERM_ENVIRON : str = "COLORTERM"
COMPONENT : str = "component"
COMPONENTS : str = "components"
CONFIG_FILE : str = "config_file"
DATA : str = "data"
DATA_DIR : str = "data_dir"
from db4e.Modules.ConstGroup import ConstGroup
from db4e.Constants.DField import DField
class DDir(ConstGroup):
API : str = "api_dir"
BIN : str = "bin_dir"
BLOCKCHAIN : str = "blockchain_dir"
DATA : str = DField.DATA_DIR
DB4E : str = "db4e_dir"
DEV : str = "dev_dir" ...
如果只有字段、标签和默认值三个大桶,就很难避免重复。我把它们按字母顺序排列,但还是会忘记已经定义过某个常量,例如 ver_p2pool 和 p2pool_ver。
代码里到处都是常量,真的无处不在。而且采用了 _FIELD、_LABEL、_DEFAULT 命名约定后,它们还特别长。LOCAL_SOFTWARE_SYSTEM_FIELD 已经够拗口,MAX_BACKUPS_DEFAULT 也好不到哪里去。显然还有什么没解决。
我尝试按领域拆分常量,但反而更糟。每个领域都有 Jobs_Fields.py、Jobs_Defaults.py、Jobs_Labels.py,让重复定义更容易发生。
使用常量的好处很快就显现出来。
采用分组常量后,VS Code 会在输入时提供自动补全建议。区别真的很明显:需要打的字少了很多(Tab 键是我的好朋友),出错机会也进一步降低。
使用常量以后,代码在编辑器里就是更好看。
不只是视觉上的改善,代码也更清晰。DStatus.ERROR、DDef.MONEROD_VER、DDir.RUN 一眼就能表达意思。
新方案还支持交叉引用。你可能注意到 DDir.DATA 是 DField.DATA_DIR 的别名。这不只是缩短名称,也有助于让代码更清楚。例如:
form_data = {
DField.NAME: DLabel.UPDATE_OPERATION,
DField.TO_MODULE: DModule.DEPLOYMENT_MGR,
DField.TO_METHOD: DMethod.POST_JOB,
DField.OP: DJob.UPDATE,
DField.ELEMENT_TYPE: DElem.MONEROD_REMOTE,
DField.ELEMENT: self.monerod,
}
我虽然定义了 DJob.OP,但它只是 OP : str = DField.OP 的别名。在这个字典里使用 DJob.OP 总觉得不合适。
Some of you may have read my Git Battles post, where I talked about how I developed and a documented a Git workflow.
I recently built MyCount to track website visitors to my projects. I found that that over 40% of my visitors were from China, and that 35% of those used a Ch...
I have a future project in mind which will require a Dynamic DNS service. I created BMDynIP for that purpose. After building the service, I wanted a simple a...
I run an NFS server on my network. I use two large drives and a cron job to rsync the data to provide basic data protection. This solution will not save you ...
I’ve been tinkering with various incarnations of Patrick Loeber’s Train an AI to Play Snake tutorial for a while now. It’s my relaxing goto project that’s fu...
This project started as a cron job and a flatfile and -honestly- that would work perfectly well for a small home setup. Say, two or three machines. I’m curre...
The Bear & Moose GeoIP Project provides an easy-to-use GeoIP service for your applications and for interactive lookups.
Our first TV was a small black-and-white thing where, on rare occasions, we’d watch Animal Kingdom. Then Beta and VHS came along, and you could watch them at...
Fr3d worked: It could talk to the Snake Lab, propose changes to the RNN configuration, run experiments, look at the results, and try again. It proved the ide...
The Snake Lab had become a proper server, with a ZeroMQ API, configuration validation, a database, and a way to run experiments independently of the client. ...
In my last post, I setup a locally hosted LLM running on an old HP Z440 and wrote a crude little conversation loop. I generated random numbers, fed them to t...
This is part one of a four part blog series. In this post, I download, install and setup some software to prompt a local LLM to write haikus…
In the first post, AI FX was still mostly a seed: a repo, a PyPI package, and an idea about using automated FOREX tooling as a learning lab. Since then, the ...
A potential client pointed me to Empowering the Energy Transition Through Fast and Flexible Network Simulation. The article describes an Open Source project,...
I have a prospective client who runs a small group of technology businesses, at least one of which integrates with clients using the Delphi programming lan...
I’ve spent some time around trading systemsL At Merrill Lynch, I supported the Order Audit Trail System (OATS), a compliance system required by NASDAQ. Its p...
A Rosebud, a Few Guppies, and a Quiet Little Ecosystem
I setup an Etsy Storefront to sell high quality, museum grade prints of some of my artwork.
I’ve been working on Db4E, my Monero deployment, operations and analytics platform. It uses Linux systemd to spin up manage Monero, P2Pool and XMRig instance...
AI Snake Lab is an interactive reinforcement learning sandbox for experimenting with AI agents in a classic Snake Game environment — featuring a live Textual...
You know that saying, “A picture is worth a thousand words.”? In programming, I’d argue it can be worth a thousand lines of code…
This post is about using constants in your code. Why it matters, what the benefits are and how you can do it well. I’m sad to say, I learned this the hard wa...
This week, I introduced 15 raccoon tiger shrimp—plus a surprise 2 bonus—to my aquarium. After a proper acclimatization, I released them into the tank… and ju...
When I first started experimenting with Monero mining and self-hosted infrastructure, I did what everyone else does: I downloaded the Monero software, the P2...
Let me be honest: Git has punched me in the face more times than I can count. Every time I think I’ve got a smooth release flow down, Git yells, “Not so fast...
I was burned by opaque documentation: I’ve been building a modern terminal UI in Python using the excellent Textual framework. It’s sharp, fast, and honestly...
The original reporting system was a set of static dashboards built using GitHub Pages, JavaScript, and ApexCharts. It pulled data from my mining setup — via ...
I’ve been deep in the trenches with my Db4E project — pulling together Monero mining infrastructure, MongoDB integration, and a bunch of orchestration magic....
I recently published a small Python module to PyPI and GitHub: db4e-systemd, a lightweight wrapper around systemctl that lets you control services (start, st...
I received my order from NIKU Farms, YAY! It’s a meat delivery that my sister, Corinna Ghaznavi, gifted me this Christmas. Every two months I receive this am...
As part of my goal to be more visible in the world, I setup this domain i.e. https://osoyalce.com. I use it to publish information about the projects I’m wor...
It’s been a while since I started and then abandoned this blog. My last post was in June of 2024!!
I decided that I didn’t like the way that the main blog page looks. I am using GitHub to host the website and am using a fork of the jekyll/minima theme. My ...
It’s in the construction phase. I need to complete the water circulation process. I bought a fiber glass kit for this (and also to fix my kitchen sink!).
The XMR Mining Farm complete with this eye-popping chart The Bear and Moose Knowledge Base My resume MyZODB - A Place to Store Everything