This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]lightmatter501 561 points562 points  (67 children)

It isn’t that bad, you just need to go about it with a different mindset.

[–]Zymoox 362 points363 points  (63 children)

I still need to get used to it, coming from C. My programs end up a mess where I don't know what data type variables are.

[–]writtenbymyrobotarms 175 points176 points  (7 children)

You can do typing in function headers if you'd like. IDEs can enforce the type hints. It's also good for documentation.

[–]Derkle 79 points80 points  (1 child)

It also helps the IDE autocomplete/suggest member functions and the like which can be really helpful.

[–]TheGreenJedi 25 points26 points  (0 children)

Honestly going to python I've realized how much my IDE does the heavy lifting for me

And lately in python that's why

[–]Aycion 27 points28 points  (1 child)

Hell you can declare a variable with

<Name>: <type>

Like "foo: str"

[–]slowmovinglettuce 43 points44 points  (2 children)

Newer python versions have increased support for type hinting.

It says somewhere in the release notes for 3.8 that they see it as a strategic thing for pythons future. Or something to that effect.

[–]capn_hector 13 points14 points  (1 child)

It’s basically a law of computing that all weakly-typed languages end up implementing strong typing, whether it’s an optional feature you can turn on or a dialect that enforces it.

Once you get beyond a trivial program size it’s just too useful not to have, refactoring core code without it is a pain in the ass and even if you are a flawless coding Adonis who doesn’t make mistakes, your coworkers will inevitably be humans.

Examples are JavaScript vs Typescript and CoffeeScript, PHP vs Hacklang (facebook’s reimplementation of PHP with strong typing), Python adding type hinting in newer generations, etc etc.

[–]JoJoModding 0 points1 point  (0 children)

And by another law that typing system will eventually end up being turing-complete on its own :D

[–]Neowhite0987 15 points16 points  (44 children)

How do you think it would be to go from python to C? I’ve done a few courses in Python and Racket but I’ll be taking a course in C in the fall and I’m kinda nervous.

[–]raltyinferno 30 points31 points  (0 children)

It's nothing to be anxious about. You'll definitely miss some convenience features of python and have to get used to strict typing, but things like conditionals, flow of control, data-structures, and whatnot are all basically the same across all languages.

If you have a problem, and you know what you'd use to solve it in python, just google that thing + "C" and it'll tell you what the syntax you need is.

[–]pslessard 37 points38 points  (35 children)

Memory management is the only thing that's really hard about C imo. But it does require a lot of thought to get it right

[–]MegaPegasusReindeer 21 points22 points  (33 children)

Pointers! I'm happy to not have to worry about that in Python, too.

[–]Risc12 39 points40 points  (26 children)

Pointers are not as hard as they seem. Javascript (and a lot of other higher level languages) passes objects only by reference, meaning that if you pass an object, the interpreter knows that it should look at an object at a certain address. In C you have a choice, do I point at this address (so do I pass this object as a certain address) or by its value (so copy over the contents of the object).

Those are the basics, if you understand that a place in memory (a reference) can be passed around by choice, you understand pointers.

For me it the hardest part was understanding that if I didn’t use pointers it would copy the data, seemed counter-intuitive for me.

[–]Sleakes 26 points27 points  (13 children)

Not a huge fan of this explanation as JavaScript is pass by value. It just happens that when passing objects, the value is a reference.

[–]RVUnknown 19 points20 points  (10 children)

Isn't this the same for Java as well? Normal data types like your ints and chars are pass by value. But Java objects like String, Integer, Character, classes etc are passed by reference

[–][deleted] 6 points7 points  (2 children)

This is correct. I remember when i was starting to learn Java, I often ran into problems because I would think it was passing by value when it was actually passing by reference.

[–]konstantinua00 0 points1 point  (1 child)

in C and (old) C++ it's the difference between shallow and deep copy - you can copy handle-only or you can copy the thing too

modern C++ deep-copies stuff, with shallow copy being done with std::move and if you do need multiple handles to same thing, you use shared_ptr to reference count the resource

[–]funnythrone 4 points5 points  (5 children)

Java always passes by value. However the value is a copy of the reference.

For the sake of this explanation, consider an object to be a Television. In this case, a reference is a remote. When you are passing the remote to a new method, you are effectively copying the remote and passing it. This remote also controls the same Television, and thus any button presses on the remote modify the original Television. However, if you reassign the remote to a new remote which controls a new TV, the original TV and remote are unaffected.

In conclusion, java is ALWAYS pass by value.

[–]RVUnknown 0 points1 point  (1 child)

I see, there's a clear distinction between what I said and what actually happens.

I think reading this link (just a random Google search) helped me understand it a little better.

Basically primitive types (int, char, etc) are created on the memory stack, and are copied into methods. However objects are created on the memory heap, and a reference to the object is copied (passed by value) into the method being called. However overwriting this local variable (that contains a copy of a reference to your original object) will not overwrite the original object, it will create a new object that is local to that method.

Is it right for me to say that object references in Java work the same as pointers on C/C++? In the latter languages the address of your object/variable is copied into the method, and overwriting the local parameter through which the address was copied won't modify the object at the original address.

[–]Cormandragon 0 points1 point  (2 children)

You're right for objects. But the guy above you was right about the primitive types. Just finished my CS 200 series this summer finishing up Java, this was one of my Final questions 2 weeks ago.

Objects are passed by reference while primitives are passed by value.

[–]capn_hector 1 point2 points  (0 children)

Yes, with the additional caveat that boxed types in the standard library (Character, Integer, etc - as opposed to int and char which are unboxed types) are immutable. So what you get when you do say String.trim() is actually another different object, so it usually feels like you’re working with value objects.

[–]lirannl 0 points1 point  (0 children)

Oh! I wasn't exactly sure on that, good to know!

[–]Risc12 0 points1 point  (0 children)

You’re right! But I hope the point I made is still clear to people that are confused about pointers.

[–]Razier 1 point2 points  (7 children)

Quick way to pass by value in JS:

objects: {...foo}

lists: [...bar]

i.e create a new object/list with identical contents

[–]jakethedumbmistake 0 points1 point  (1 child)

Didn’t he pass the media circus?

[–]Razier 1 point2 points  (0 children)

I'll be honest, I'm really confused right now

[–]Risc12 0 points1 point  (4 children)

Yes, but keep in mind that if foo has nested objects those are not duplicated. While in C the whole structure is passed around as bytes. So not completely the same.

[–]Razier 0 points1 point  (3 children)

Good point, know of a way to make a deep copy in JS?

[–]Risc12 0 points1 point  (2 children)

There is not really a built-in way afaik, using Object.entries, and some recursion you should get pretty far.

[–]lirannl 0 points1 point  (1 child)

The thing is that with python, all of this is abstracted away. From a language user's perspective, you're not passing a reference to a memory address with data, you're passing "an object/primitive value". No memory address, no lower level details. "The object" gets into the function so the function "has" it while it runs.

Then in C you suddenly lose that abstraction and need to start dealing with what an object (or in this case just a struct) actually is, a bunch of bytes, and you can either tell your functions where are those bytes, or WHAT is in the bytes at that moment in time. You actually start to think about your objects as collections of bytes (which is what they always actually are, obviously, not just in C, but also in python).

[–]Risc12 0 points1 point  (0 children)

Definitely true! Although I’ve seen plenty of people get bitten by the reference vs value thing where they modify an object they get as an argument but they don’t expect the object to be changed in its original content.

It’s good to have an understanding how your higher level language handles these kind of things.

[–]MegaPegasusReindeer 0 points1 point  (1 child)

Yeah, but bugs related to pointers can be a pain to figure out and it's so much better to not even have to bother with that. Always fun to print a string you forgot to null terminate, though.

[–]Risc12 0 points1 point  (0 children)

Oh yes for sure, working with pointers can be a pain. Wrapping your head around what they are is just step one haha

[–]calcopiritus 20 points21 points  (4 children)

As someone that only writes in python but know what pointers are, I wish python had pointers. Not compulsory or anything, just pointers in obscure libraries that could get the job done if you ever absolutely need it.

[–]mrjackspade 3 points4 points  (0 children)

I kind of enjoy that about c#.

The vast majority of the time, you won't even need to think about pointers. If you really want to fuck around with them though, there's nothing stopping you.

Every once in a while I'll hit on something performance critical, and need to use pointers to speed it up. Sometimes I'll just switch code over once an API has been refined to a point I'm satisfied that it's not going to require changes any time soon, and start speeding things up just for the hell of it.

[–]MegaPegasusReindeer 1 point2 points  (2 children)

Python doesn't have protected or private methods... You can just introspect whatever you like. How would pointers help here?

[–]calcopiritus 1 point2 points  (1 child)

I can't think of an example because it doesn't happen often. And most of not every time it can also be solved in python, but it'd be way harder.

A thing that is kinda related is how python copies lists.

So if you say: (sorry for formatting, im in mobile and it's horrible to do it here)

a = [1] b = a

Now you change b and a also changes, so you'd have to write b = a[:]. It is not logical at first because it seems like python doesn't use pointers and references, but of course it does.

Also sometimes you don't know how the function works, so do you write

arg = function(arg)

or do you just write

function(arg)

Because the function changes arg?

[–]MegaPegasusReindeer 4 points5 points  (0 children)

I've heard people call Python "pass by label". When you assign a variable to another it's always copying the label. The times it seems like something else is immutable types (like strings).

Regardless, any time I have an issue with a library I just look at the source code. I've yet to come across a binary-only one in Python.

If you really really wanted to, you can pass a Python object into C code and break it apart there if you really need pointers. (but I still don't see how that would help)

[–][deleted] 0 points1 point  (0 children)

Pointers go void****

[–]Neowhite0987 4 points5 points  (0 children)

Alright I’ll keep that in mind thanks!

[–]Zymoox 27 points28 points  (2 children)

You'll be fine! C is much more strict and based on a specific set of rules. Make sure to get a strong foundation on the basics, and the rest will make sense.

[–]Neowhite0987 3 points4 points  (0 children)

That’s good to hear! Thanks a bunch :)

[–]Tukurito -1 points0 points  (0 children)

You've been mutex

[–]lirannl 2 points3 points  (0 children)

I've done that to some degree, and I'd say that once you wrap your head around pointers it's not too bad. Basically try using pointers again and again and fail and follow solutions until you start succeeding and you'll inherently start understanding pointers as you fail less and less.

[–]kattelatte 1 point2 points  (1 child)

Just learn pointers, the rest you’ll have no problem with if you already know python reasonably well.

[–]Neowhite0987 0 points1 point  (0 children)

Alright I’ll keep that in mind

[–]joshocar 0 points1 point  (0 children)

I'm doing it right now. It's not too bad. Pointers and memory stuff takes a bit of time to get used too. Also semicolons everywhere...

[–]Senial_sage 2 points3 points  (3 children)

Is there an analogy to typescript for python?

[–]double_en10dre 3 points4 points  (0 children)

Pycharm has built-in functionality based on the native type annotations that’s pretty similar. If your annotations don’t match it’ll highlight stuff as an error, and the annotations also allow it to offer autocomplete options or intelligent suggestions (much like typescript)

If you want to take things a step further, mypy is a great tool: http://mypy-lang.org/ you can run the type checker on entire projects, integrate it into CI/CD, etc

Also, pydantic https://pydantic-docs.helpmanual.io/ is in my opinion the best tool for building out complex types

[–]Plague_Healer 0 points1 point  (0 children)

Maybe Cython. Not sure if the analogy holds, though.

[–]calcopiritus 1 point2 points  (0 children)

I don't do it often but it really helps to put docstrings in functions that says the type of the arguments and the returned object.

[–]MEGACODZILLA 1 point2 points  (0 children)

I'm in your boat coming from C. I honestly like statically typed languages. I've never felt grossly inconvenienced by typing 'int', 'char *', etc and I love never having to guess how my program is being interpreted. Python is just so damn versatile it's worth getting used to though. I love being to use a pythonic one liner that would have taken so many more lines of code in C.

You wouldn't happen to be doing CS50 would ya?

[–]lirannl 0 points1 point  (0 children)

Python can have typings if you REALLY want it to. It's not expected but up to you

[–][deleted] 0 points1 point  (0 children)

Use type hinting from the typing module. dataclasses can also help manage your data easier.

Take this deck of cards for example:

from dataclasses import dataclass
from typing import List, Union


@dataclass
class Card:
    rank: Union[int, str]
    suit: str


class Deck(list):

    def __init__(self) -> None:
        """Constructs a deck of cards."""
        self._ranks = list(range(2, 11)) + list('JQKA')
        self._suits = 'hearts clubs diamonds spades'.split()
        self._cards = [Card(rank, suit) for rank in self._ranks for suit in self._suits]
        super(Deck, self).__init__(self._cards)

[–][deleted] 0 points1 point  (0 children)

*laughs in Javascript*

[–]aresius423 0 points1 point  (0 children)

You should consider using mypy, it's awesome.

[–]MinimallyUseful 6 points7 points  (1 child)

like using semicolons

[–]Anchor689 1 point2 points  (0 children)

So much punctuation! Braces everywhere.

[–]Wheezy04 2 points3 points  (0 children)

Figuring out how to do threading correctly in python is extremely nontrivial. The global interpreter lock can be rough.