Python variables are bound to types when used?
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Wed Oct 19 16:54:16 EDT 2005
In <1129751462.061785.124830 at g49g2000cwa.googlegroups.com>, pranab_bajpai
wrote:
> So I want to define a method that takes a "boolean" in a module, eg.
>
> def getDBName(l2):
> ...
Is that a 12 or l2?
> Now, in Python variables are bound to types when used, right?
>
> Eg.
> x = 10 # makes it an INT
> whereas
> x = "hello" # makes it a string
No, think of `x` as a *name*. The name has *no* type. The objects you
bind to that name have a type. So 10 is an int and "hello" is a string.
> I take it, the parameters to a function (in the above example "l2") are
> bound in the definition, rather than as invoked.
If you invoke the function then the parameter is bound to an object. This
object has a type.
> So, if I use "l2" thus:
>
> if (l2): # only then does it make it a boolean?
Here `l2` is treated as a boolean. If it is an integer then 0 is false,
everything else is true, if it is a list, dictionary or string then an
"empty" object is false, everything else is true. Otherwise it depends on
the existence and return value of either a `__nonzero__()` or the
`__len__()` method. See the docs for details.
> and if I did,
>
> if (l2 = "hello"): # would it become string?
It would become a syntax error. No assignement allowed there.
> and what if I never used it in the definition body?
Again: The objects have types, the names not. A string that is never used
remains a string.
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list