Python Newbie

E

Ethan Furman

Indeed the assignment is enough to deduce "intX" is an int. The comment is there to let me know it is unlikely intX appears earlier in the code. Please, let me do things my way until I find reasons to the contrary.

Of course you can, but wouldn't you rather find reasons to the contrary by us telling you, instead of tripping
over something yourself?

For example (I believe it's already been mentioned) "declaring" intX with some integer value does *nothing* to maintain
X as an integer:

--> intX = 32
--> intX = intX / 3.0
--> intX
10.6666666666
 
P

piterrr.dolinski

For example (I believe it's already been mentioned) "declaring" intX with some integer value does *nothing* to maintain
X as an integer:

--> intX = 32

--> intX = intX / 3.0

--> intX

10.6666666666

Yes I did see that it is possible to redefine the type of a variable. But I don't think I would ever do this intentionally; need to be really careful with Python.

Peter
 
P

piterrr.dolinski

For example (I believe it's already been mentioned) "declaring" intX with some integer value does *nothing* to maintain
X as an integer:

--> intX = 32

--> intX = intX / 3.0

--> intX

10.6666666666

Yes I did see that it is possible to redefine the type of a variable. But I don't think I would ever do this intentionally; need to be really careful with Python.

Peter
 
J

Joshua Landau

with some integer value does *nothing* to maintain

Yes I did see that it is possible to redefine the type of a variable. But
I don't think I would ever do this intentionally; need to be really careful
with Python.


Not necessarily.

Python duck types. If you don't know what that means, Google's got a ton on
it.

Take a look at my really bad quadratic equation solver. It supports integer
input, float input and complex input. It will output a list of two floats
or complex numbers.

That's a use for having one variable have different types. You'll find
thousands of parallels in real, working code.

Hence, you don't really need to be careful. You'd probably benefit if you
stopped thinking of supporting type-changing as "dangerous" and started
thinking of it as "useful".
 
E

Ethan Furman

Yes I did see that it is possible to redefine the type of a variable.

And that right there is one of the key aspects of Python: there are no variables, only objects, and objects' types
cannot be changed. objects can be labeled with names, but the names are more like sticky notes, and can be peeled off
and stuck on some other object.
 
M

Mark Lawrence

Yes I did see that it is possible to redefine the type of a variable. But I don't think I would ever do this intentionally; need to be really careful with Python.

Peter

Yes this is a big downside with Python. Sadly it means us poor Python
programmers have to waste a lot of time and effort testing our code,
unlike those who use statically typed languages which work perfectly
once they've been compiled.
 
R

Roy Smith

Ethan Furman said:
Of course you can, but wouldn't you rather find reasons to the contrary by us
telling you, instead of tripping
over something yourself?

For example (I believe it's already been mentioned) "declaring" intX with
some integer value does *nothing* to maintain
X as an integer:

--> intX = 32
--> intX = intX / 3.0
--> intX
10.6666666666

I could imagine a getattr-based implementation of DBC (Design By
Contract) which does use the variable name to enforce type. Unclear if
this is a Good Thing, a Bad Thing, or a just plain Crazy Thing. In any
cae, it would be a neat (if somewhat advanced) exercise for somebody
interested in enforcing types and looking to explore some of the more
arcane corners of Python.

class DBC_Example:
# Ad-libbing this, code not tested
def __setattr__(self, name, value):
if name.startswith('int'):
assert isinstance(value, int)
self.__dict__[name] = value
 
S

Steven D'Aprano

Well, not quite everything. If I write:

if foo:
do_this()
and_this()

the code block making up the body of the "if" statement is not an
object. In some languages, it is.[/QUOTE]


In Python, that code block isn't any *thing*. It's merely a small part of
the enclosing code block, which *is* an object.

When we say "everything is an object" in Python, we're talking about
values, not arbitrary language constructs. The "*3" bit of "y = x*3" is
not a value, a for-loop is not a value, and the delay you experience when
you call time.sleep(30) is not a value, so none of these things are
objects. This is not to reduce the importance of these things as
programming concepts, but they aren't the kind of things we mean when we
say everything is an object.
 
O

Oscar Benjamin

Yes I did see that it is possible to redefine the type of a variable. But I don't think I would ever do this intentionally; need to be really careful with Python.

You do need to be careful around types in Python (as in all
languages). It took some time for me to understand how to use types in
Python. After a while I came to realise that not knowing exactly the
type of a particular object is not as much of a problem as I initially
thought. Once you understand how to use this ambiguity to your
advantage it becomes possible to write very flexible code that can be
reused without ambiguity in situations that you haven't yet
anticipated.

The key mental hurdle, I think, is to realise that instead of relying
on compilation errors to spot (a small subset of) your programming
errors, you are relying on runtime exceptions. Python still gives
errors when you use an object in a way that is inconsistent with its
type; you just don't see those errors at compile time.

The trickier cases are ones where two types are very similar and can
be used similarly in most, but not all, situations. An example of this
would be the one that Chris has highlighted where an object that you
expected to be an int is actually a float. I find that I need to be
careful when using division on quantities that I expected to be
integers (true in all languages) and careful about the notation used
in a numeric literal. Once you get used to it, you will find it easy
to see that the '.0' that Chris appended was deliberate in order to
control the type of the resulting object.


Oscar
 
R

Roy Smith

Yes I did see that it is possible to redefine the type of a variable. But I
don't think I would ever do this intentionally

One does not need language features to protect themselves against things
they do intentionally. They need language features to protect
themselves against things they do by accident. Different languages
protect you from different things.

Compare, for example, C++ and Python.

C++ protects you against accidentally passing an int where you were
supposed to pass a float. Well, no, with automatic type promotion,
that's a bad example. But it does prevent you from passing an IntThing
where you were supposed to pass a FloatThing (assuming IntThing is not a
subclass of FloatThing, and a few other details).

But, Python protects you from dereferencing a null pointer, or
double-freeing a pointer. There's just no way to even write those
concepts in Python.

You pays your money and you takes your chances. Pick which type of
protection you feel is more important and use the language which gives
you that.
need to be really careful with Python.

You need to be really careful with all programming languages. You just
need to be careful about different things.
 
S

Steven D'Aprano

Yes I did see that it is possible to redefine the type of a variable.

Variables do not have types in Python.

Reset your thinking. Python is a dynamic language with name bindings and
strongly-typed objects, not a static language with strongly-typed
variables. If you don't understand the difference, ask. But so long as
you make the wrong assumptions about the language, you will have a bad
time.

You will find programming much easier, and more pleasant, if you learn
the semantics and idioms of the language you are using, instead of trying
to treat every language as the same.

But I don't think I would ever do this intentionally; need to be really
careful with Python.

Not at all. The only difference is whether you get a compiler error or a
runtime error. Instead of:

10 Write code.
20 Compile.
30 If compiler error, GO TO 10.
40 REM code compiles, but it still needs to be tested
50 Test code.
60 If error, GO TO 10.
70 Deploy.

we have:

10 Write code.
20 Test code.
30 If error, GO TO 10.
40 Deploy.
 
S

Steven D'Aprano

Mark,

Back in the day when C was king, or take many newer long established
languages (C#, Java),

Python is older than either C# or Java. Why have those languages paid no
attention to the innovations of Python, instead of copying the
misfeatures of C?

Pascal and Algol and Fortran are older than C. Why did C introduce
unnecessary brackets when these older languages did not need them?

the use of () has been widespread and mandated by
the compilers. I have never heard anyone moan about the requirement to
use parentheses.

You have not been paying attention.

In many ways, C has been a curse on programming. It has trained large
numbers of coders to expect and *demand* poor syntax.

Now come Python in which parens are optional, and all
of a sudden they are considered bad and apparently widely abandoned. Do
you really not see that code with parens is much more pleasing visually?

That's funny. Perhaps you should be programming in Lisp.

I could understand someone's reluctance to use parens if they are very
new to programming and Pythons is their first language. But my
impression here is that most group contributors are long-time
programmers and have long used () where they are required. Again, I'm
really surprised the community as a whole ignores the programming
"heritage" and dumps the parens in a heartbeat.

(Because they are unnecessary) (visual noise) (that don't add anything)
(useful) (to the reader's understanding) (of the code).
 
S

Steven D'Aprano

But if block doesn't have to be inside a function, right? It needs to be
inside a module, but then again everything is inside a module, but it
wouldn't be very object-oriented if the module was the only object in
Python :).

Python doesn't have code blocks as distinct values. I suppose you could
fake it using compile() and eval() by hand, but it wouldn't work very
well.

Ruby-style code blocks have been requested for many years. GvR has given
his support to this *in principle*, but it depends on somebody thinking
up decent, unambiguous syntax that works with the rest of Python.
 
C

Chris Angelico

Not at all. The only difference is whether you get a compiler error or a
runtime error. Instead of:

10 Write code.
20 Compile.
30 If compiler error, GO TO 10.
40 REM code compiles, but it still needs to be tested
50 Test code.
60 If error, GO TO 10.
70 Deploy.

we have:

10 Write code.
20 Test code.
30 If error, GO TO 10.
40 Deploy.

The advantage of compile-time errors is that you don't have to wait
for *that branch* to be executed. So they're hugely advantageous when
it comes to the "obvious problems" like syntactic errors... and looky
here, Python does exactly that :) The only difference between "static"
and "dynamic" is how much is done at each phase.

If your program has no inputs or side effects, the compiler could
theoretically convert it into a single static output statement. Voila!
All your run-time errors have become compile-time errors. Conversely,
you could compile your application from source just before running it.
Voila! Everything's a run-time error, even the omission of a semicolon
in C. Okay, both of those are pretty stupid examples, but there's
really no fundamental difference.

ChrisA
 
M

Michael Torrie

I wanted Python to register what type of variable I'm after. So I
init my vars accordingly, int might be 0, float 0.0 and string with
null, err... None.

As several people on the list have pointed out, there are no variables
in Python. Let me repeat that. There are no variables in python. Thus
to say, x=5 does not tell anything about what x can represent in the
future. It merely says that the *name* "x" is bound to the object,
which happens to be an immutable integer object that represents 5. That
5 can never change. Ever. In the future you can assign x to another
object, maybe the result of an expression. So none of what you did
"initialializes" a "variable." Probably sounds like I'm just being
pedantic, but if you can learn to see the wisdom and strengths of
python's way of doing things you'll end up writing very rapid code and
very correct code too.

Python's type system is dynamic but it is, in fact, a strong type
system. You can't just arbitrary convert an object from one type to
another. The aspect of python that gives it so much power over
statically-typed languages is that as long as a type supports the
interface you want to work with, the type just doesn't matter. Nor
should it. This allows tremendous code re-use. For example I can
totally change out one object for another object of a completely
different type and my algorithms and logic still work. It's similar to
C# generics, but much more powerful. In Python, it's called
duck-typing. It's a very powerful concept.
 
M

Michael Torrie

But if block doesn't have to be inside a function, right? It needs
to be inside a module, but then again everything is inside a module, but
it wouldn't be very object-oriented if the module was the only object in
Python :).

A module indeed fits into the OOP paradigm. It's called a singleton and
I love the fact that I can define and use them in python without
wrapping them in tons of boilerplate class and factory code.
 
M

Michael Torrie

Variables do not have types in Python.

Reset your thinking. Python is a dynamic language with name bindings and
strongly-typed objects, not a static language with strongly-typed
variables. If you don't understand the difference, ask. But so long as
you make the wrong assumptions about the language, you will have a bad
time.

Yes, but according to my computer language theory class, strictly
speaking, python has no variables, only names and objects, which for the
most part aren't mutable. A variable by definition is a box in memory
that you can write to. The closest thing python has to that are
instances of mutable types like a list.

"a=5" certainly doesn't allocate a box in memory somewhere and stick 5
in it. And then later "a += 1" or "a=6" doesn't mutate the value stored
in the box represented by a. Instead it allocates a new object and
makes a refer to that new object.

I know all this is what you meant, but with the original poster's
frustrations with python, it's important that he just throw out the
notion of variations entirely because sooner or later that will get him
in trouble here, like if he tries to make an empty list be a default
value for a function parameter.
 
D

Dennis Lee Bieber

It's interesting to note that Windows NT sort of descends from VMS. I
guess the end result was an unholy blend of VMS and CP/M.

Pity they didn't take the "good parts" of VMS...

Interprocess communication via "mailboxes" would have been nice...
More general than UNIX-style "pipes", as once the mailbox has been
created, multiple processes could connect for read or write in parallel.
Processes don't have to be blocked by mailbox I/O...
 
J

J.R.

On 21/02/2013 19:40, (e-mail address removed) wrote:

I am nervous about using variables "out of the blue", without having
to declare them. For example, when I write "i = 0" it is perfectly OK
to Python without 'i' being declared earlier. How do I know that I
haven't used this variable earlier and I am unintentionally
overwriting the value? I find I constantly have to use the search
facility in the editor, which is not fun.

You see, Javascript, for one, behaves the same way as Python (no
variable declaration) but JS has curly braces and you know the
variable you have just used is limited in scope to the code within
the { }. With Python, you have to search the whole file.

No, JavaScript - or better, ECMAScript -, does have variable
declaration. If you don't declare a variable with the "var" statement it
will become an unintentional global variable which is a very bad thing.

If the variable statement occurs inside a Function Declaration, the
variables are defined with function-local scope in that function.
Otherwise, they are defined with global scope (that is, they
are created as members of the global object. Variables are created when
the execution scope is entered. A Block { } does not define a new
execution scope.

PS.: JavaScript is a trademark, and the actual language name is
specified as ECMAScript.

See <http://ecma-international.org/ecma-262/5.1/>
 
R

Roy Smith

J.R. said:
PS.: JavaScript is a trademark, and the actual language name is
specified as ECMAScript.

The decision whether to call it JavaScript or ECMAScript really comes
down to, "Do you want to be correct, or do you want people to know what
you're talking about?"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top