Python variables are bound to types when used?

Grant Edwards grante at visi.com
Wed Oct 19 16:06:53 EDT 2005


On 2005-10-19, pranab_bajpai at yahoo.com <pranab_bajpai at yahoo.com> wrote:

> So I want to define a method that takes a "boolean" in a module, eg.
>
> def getDBName(l2):
> ...
>
> Now, in Python variables are bound to types when used, right?

Python doesn't have variables.

Python has objects of various types.  You can bind 0 or more
names an object.

> Eg.
> x = 10 # makes it an INT
> whereas
> x = "hello" # makes it a string

No, not really.  There is no "it" that's becoming different
types.

  x = 10

creates an integer object with the value 10 and binds the name
"x" to it.

 x = "hello"

creates a string object containing the value "hello" and then
unbinds the name "x" from the integer object and re-binds it to
the string object.  [At that point, the integer object _may_
get deleted if it's not being used any longer (it may have had
multiple names).]

> I take it, the parameters to a function (in the above example "l2") are
> bound in the definition, rather than as invoked.

Not sure I understand the question.  The function you defined
accepts a single object as a parameter.  When the function is
invoked, that object has the local name "l2" bound to it 

> So, if I use "l2" thus:
>
> if (l2): # only then does it make it a boolean?

That doesn't affect the type of the object with the name "l2"
at all.  It checks to see if l2 has a false value or not.
Examples of basic objects with false values are an iteger 0, a
floating point 0.0, an empty string "", an empty list [], an
empty tuple (), or an empty dictionary {}.

> and if I did,
>
> if (l2 = "hello"): # would it become string?

That's not legal python.  I presume you mean

  if l2 == "hello":

The expression

  l2 == "hello"

checks to see if the object with the name "l2" is a string with
the value "hello".  If the object you passed to the function is
a string object with the value "hello", that experession will
be true.  The expression will be false for any object that
isn't a string, and false for any string object that doesn't
have the value "hello".

> and what if I never used it in the definition body?

Then it doesn't get used.

-- 
Grant Edwards                   grante             Yow!  I just forgot my
                                  at               whole philosophy of life!!!
                               visi.com            



More information about the Python-list mailing list