# Function behaves differently inside a package than outside

I defined a function TestHead in a notebook as follows:

TestHead[z___] := TrueQ[{z} == Cases[{z}, x_ /; Head[x] === avar]]


to test whether a bunch of variables all have a certain head avar. When I do this in a notebook and define a variable a using

a /: Head[a]=avar


this works fine and gives True for TestHead[a]. However, when I make a package

BeginPackage["TestHead"]
Begin["Private"]
End[]
EndPackage[]


load the package and again define a variable a as above, the function TestHead now gives False when acting on a.

Why is this and how I can remedy it?

-

It's because avar is in the TestHeadPrivate context. One fix is to write your package with an explicit context on avar, such as Global:

TestHead[z___] := TrueQ[{z}==Cases[{z},x_/;Head[x]===Globalavar]]


You could have debugged this for instance with Trace and you would have seen instantly, why your SameQ results in False:

Trace@TestHead[a]

(*
{TestHead[a],TrueQ[{a}==Cases[{a},TestHeadPrivatex_/;Head[TestHeadPrivatex]
===TestHeadPrivateavar]],
{{Cases[{a},TestHeadPrivatex_/;Head[TestHeadPrivatex]===
TestHeadPrivateavar],{{Head[a],avar},avar===TestHeadPrivateavar,False},{}},
{a}=={},False},TrueQ[False],False}
*)

-
The other possibility, of course, is to have avar be declared by the package (it will thus be under the TestHead context, i.e. its full declaration is TestHeadavar):
BeginPackage["TestHead"]
Begin["Private"]