Creating a variable of a specific type
Diez B. Roggisch
nospam-deets at web.de
Thu Feb 5 07:56:34 EST 2004
> I understand that Python is strongly, but also dynamically typed. However,
> I need to create a variable which initially isn't actually set to
> anything, but still needs to be of a certain type. I've looked around a
> bit, but I'm not entirely sure how to do this.
>
> Specifically, I have a bit of C++ code which says:
>
> struct in_addr ipAddress;
> struct sockaddr_in serverAddress;
> map<int, socklen_t> clientAddressSizes;
> fd_set primarySocketTable;
> map<int, pthread_t> socketThreads;
>
> ...this is an except of a sample of different types that I am using. From
> looking at the documentation for the Python socket module, for instance, I
> can see that the function socket.inet_ntoa() requires a variable in struct
> in_addr form, just like in C++. The difference is that I don't know how to
> set up a 'blank' variable, if you see what I mean!
>
> I'm sure it's just a simple thing that has eluded me somehow, but in
> addition to answering this question if anyone can speak any wisdom about
> the other data types I have listed above, and their equivalents in Python,
> that would be helpful.
While your are right that python is strong and dynamically typed, you have a
(very common) misconception about variables in python. In python, you have
values on the one side, and _names_ that are bound to certain values on the
other side. So
a = 10
a = "20"
is perfectly legal - and there is no way of limiting the types of values
bound to a (which is what you are asking for). Now while this might look
like weak typing, its not, as this example shows:
a = 10
b = "30"
a + b
TypeError: unsupported operand type(s) for +: 'i
That would go with perl or tcl - and even C! In c, the example would more
look like this:
int a = 10;
char *b = "30";
a + b;
This compiles without any complaints....
Now back to your problem: I don't know right from my head what socket
requires as inet-type, but I guess its a tuple of some sort. You don't need
to declare a variable for that - just use it. If you need to check for a
symbol not beeing initialized, simply use None as value, like here:
address = None
if address:
do_something(address)
None is considered false. You might be more explicit, by using
if address == None:
but thats a matter of taste (to me, at least...)
--
Regards,
Diez B. Roggisch
More information about the Python-list
mailing list