A moving weight in the head wouldn't really work, because it'd just jerk the head. (I mean, put a marble inside a larger ball, then rattle it around; that's what it'd feel in your hand. No swing, just short jerks.)
You might get something out of a mallet with a gyroscope, though. The gyroscope axis must be perpendicular to the hammer swing plane, or it literally makes the mallet un-swingable. Which in itself could be a funny gag; although the suitcase version is well known:
The trick with the flywheel gyroscope in a mallet is that it'd need huge acceleration and deceleration. The change in the angular momentum means the mallet would feel like it was trying to swing.
Of course, it would be doubly hard to aim, because changing the swinging plane introduces precession (which causes the swinging/rotating tendency in the suitcase gyroscope). You'd have to have a really strong motor, trying to accelerate then decelerate (powered deceleration, not just shorting out the magnetic field) in a rather rapid sequence, say half a second heavy acceleration, then half a second heavy deceleration, and so on.
It would not help with hammering action, it would help with the angular momentum involved in the swing.
You'd probably want to use a BLDC motor for this. I don't know if there are bearings that could take the hammering action (the rotation axis is planar to the surface being hit, though).
But yeah, you can make a larger mallet that wants to swing. Hammer, no, because there is not enough room in it for a flywheel and a motor. Linear element would not induce any swing, just small jerks.