Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Dominoes
Sep 20, 2007

CAO Apr 2020
Python code:
import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
About
Python’s a high-level language that’s easy to learn, read, and write. It’s popular, has a robust collection of third-party modules, and a large community willing to help. It’s friendly to multiple programming styles: procedural and functional; object-oriented, and not. Generally, it runs slowly compared to other languages like C, Go, Java, Julia, Rust, and Haskell.

Python is versatile, and is especially popular for scientific computing and web development. It’s not suitable for systems programming, and is weak when making distributable stand-alone programs.

What makes Python different from other languages?
-Significant whitespace. In other words, you don’t use braces to indicate blocks of code, you use indentation.
-Duck typing: Python doesn’t care about the actual type of the objects you’re working with as long as the object implements the correct attributes and methods. Python is also strongly typed, meaning that you can’t can add a string, a number, and a file object together to get some guessed-at result.
-Extensive standard library.

Python has a split userbase between (incompatible) versions 2 and 3. Many old code bases use v2. Highlights: The versions handle character encoding differently, v3 uses lazy evaluation in the standard library when possible, and v3 includes many new features.


General links


Learn


Installing Python and third-party packages
There are two main paths for installing Python. If you’re new, download Anaconda; it has many common third-party packages built-in. You can install additional packages later, with its conda package manager, or using the official one, pip.

You can also install Python directly from the Official downloads page.The default links on this page are for x86-versions; browse to the OS-specific pages to find the 64-bit downloads.

If you’re on Linux, you probably have Python installed already – perhaps multiple versions. Using virtual environments is especially important on Linux; altering the system python may break your OS. See the Virtual environments section below.

Third-party packages can be installed with the built-in package manager pip. Run pip install packagename. Or create a text file of package names, and install with pip install -r requirements.txt. Anaconda users can install most packages with conda install packagename.

Consider using Poetry or pipenv to install packages, rather than using pip and virtual environments separately. Use commands like this: pipenv install requests, or pipenv install, if you already have a pipfile established. (pipenv creates and manages this file automatically).


Selected third-party packages
  • Requests - for making web requests with easy syntax
  • Pytest - unit tests; cleaner than the built-in module.
  • SQLalchemy - for working with databases.
  • BeautifulSoup - for parsing HTML and XML. Recommended over a built-in alternative
  • Websockets – Live communication betweeen browser and server.
  • PyQt5 Lets you use the C++ GUI library Qt with Python. Steep learning curve, but QT is a powerful, well-documented way to make desktop and mobile GUIs. Used by Matplotlib, Ipython Qtconsole, and Spyder.
  • Toolz - functional programming tools like currying, accumulate, take, compose, and pipe. Some of this functionality's included in the built-in itertools and functools libraries, or is easily created from them. You should check those libraries out too!


Virtual environments
Using virtual environments lets you isolate a project's dependencies from your system's Python installation. This is important on Linux, where altering the system Python can break your OS, and useful on any OS to keep packages separate and easy-to-manage.

Official python virtual environment reference. Consider using pipenv instead of this directly; it combines workflows for package management and virtual environments. You can access the environment from a terminal using commands such as pipenv shell, or pipenv run, followed by a command.

Anaconda has its own virtual-environment tools.


Scientific computing
The Scipy Stack is a collection of modules that expand python’s numerical-computing capability. They work well together, but learning when to use each package can be tricky. The Python Data Science Handbook, linked below, can help. All of these packages can be installed with conda; most with Pip.

Numpy: Provides a multi-dimensional array data type that allows fast vectorized options. Great for linear algebra, and nearly all numerical computing in Python relies on it.

Scipy – A collection of unrelated tools, divided into submodules. Includes modules for statistics, Fourier transforms, scientific constants, linear algebra, signal processing, image manipulation, root-finding, ODE-solvers, and specialized functions (Bessel etc) etc. If you're considering implementing a common scientific operation by hand, check Scipy first.

Matplotlib– Plotting. Robust and flexible. Has two APIs, both of which are awkward.

Sympy – symbolic computation. Manipulate equations abstractly, take derivatives and integrals analytically, manipulate variables.

Pandas – Used in statistics and data analysis; wraps Numpy arrays with labels and useful methods.

Ipython / Jupyter. Exists as three related components: Ipython terminal: A powerful improvement over the default. Ipython QtConsole: Similar to the terminal app, but has advantages provided by a GUI. Notebook: Work on pages of mixed code, LaTeX, and text on redistributable web pages. Set to be replaced by a new project called Jupyter Lab

Related: Scikit-learn is a machine-learning package with a simple API. Solves classification, regression, and clustering problems with a range of techniques. Tensorflow and Theano provide neural net frameworks.


Code editors
  • PyCharm Robust and full-featured. Its community edition is free, and works well for Python. Its Profession edition costs ~$60/year, and includes addition features like web-development tools. Free for students and contributors to open-source projects.
  • Spyder is targeted at scientific computing, and is simpler than PyCharm. Can be installed with pip, and is included with Anaconda.
  • If you'd prefer a text-editor with language-specific features, try Visual Studio Code.


Web development
Python is great for server-side web development, when paired with one of these packages:
  • Django – Batteries-included and popular. Intimidating to start with, and involves many files working together, but includes most of what you need to build a website. Extensive docs, and many people who can help on StackOverflow.
  • Flask Minimalist, and easy to start with. Customizable. As your projects grow, you’ll likely want to add other modules for things like database management, migrations, admin, and authentication.
  • Pyramid and Pylons are other popular frameworks.This page shows an overview of what's available.

Warning: Diving into these packages directly can be challenging if you’re new to web development, since it requires proficiency in several skills. I recommend learning Python, database basics, HTML, CSS, and Javascript independently first. Check out Tango with Django for a Django tutorial. huhu posted a Flask intro in this thread.

Heroku is a service that makes hosting Python websites easy; it has free plans for development, and can quickly scale up for production use.

Microcontrollers
Micropython allows you to run Python on embedded systems.

Additionally, Python has good library support on single-board-computers like the Rasperry Pi.
Alternatives
For scientific computing: Julia is fast, and has more natural syntax for math and equations. Similar syntax to Python; it’s easy to pick up one if you know the other.
code:
f(x) = 2x^2
Python code:
f = lambda x: 2 * x**2
Prototyping, and other fast-to-develop programs that compile to native binaries: Go.

Pure functional programming: Haskell has a steep learning curve, and is a robust functional language. Is a high-level langauge like Python.

Statistics and data analysis: R. Specialized, popular language with a large collection of stats packages.

Web development: Ruby on Rails is another high-level framework with nice syntax.


Complementary languages
  • C: Python runs on C, so it's a natural language to write high-speed extensions in. Rust provides a modern alternative.
  • HTML, CSS, and Javascript for web development.
  • SQL, if you use Python to manage databases.


Expanding Python into new realms
  • PyPy is a Just-in-time (JIT) compiler for Python that allows a subset of the language to run very fast.
  • Numba is another way to speed up Python to near-C-speeds with a JIT. By applying a decorator, it can make python functions run much faster, but limits which parts of the language you can use in these functions. It usually requires writing loops manually, where otherwise you might used vectorized code.
  • Micropython allows you to code custom microcontrollers with Python.


Neat specialized tutorials



(By Randall Munroe)

This OP’s a community effort; PM me for updates and edits.

Dominoes fucked around with this message at 16:22 on Apr 23, 2020

Adbot
ADBOT LOVES YOU

tef
May 30, 2004

-> some l-system crap ->
RIP The old thread.

To open the new thread, here's something I wish I knew all those years ago:


code:
a_string = (
    "One"
    "Two"
    "Three"
)
Gives "'OneTwoThree"

Hammerite
Mar 9, 2007

And you don't remember what I said here, either, but it was pompous and stupid.
Jade Ear Joe

tef posted:

RIP The old thread.

To open the new thread, here's something I wish I knew all those years ago:


code:
a_string = (
    "One"
    "Two"
    "Three"
)
Gives "'OneTwoThree"

Potentially a double-edged sword, because if I try to write a list of strings as in

code:
a_string = (
    "One",
    "Two",
    "Three",
)
and I screw up by omitting a comma somewhere in the middle, I could see unexpected results.

Lysidas
Jul 26, 2002

John Diefenbaker is a madman who thinks he's John Diefenbaker.
Pillbug
I don't use pylint, only the linter that's built in to PyCharm -- does pylint flag implicit string concatenation? At first glance it seems tricky to figure out when it might be intentional, since I relatively commonly do

Python code:
p = ArgumentParser()
p.add_argument(
    '--some-option',
     help=(
        'a long description that '
        'I split across multiple lines'
    ),
    action='store_true',
)
but I virtually never want implicit string concatenation in a List[str] like

Python code:
some_strings = [
    "One",
    "Two",
    "Three",
]
so it seems like I'd get a lot of use out of a simple heuristic like "found implicit string literal concatenation inside a list literal without enclosing parentheses".

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

What I normally do is type out my longass string and then find spots in it that make sense to break it up. Then I put the cursor there and press enter and PyCharm moves it all to the next line while taking care of quotes.

Also, for whatever reason I find myself using long strings as function params (logging usually) more often which doesn't require the extra set of parentheses which is nice.

QuarkJets
Sep 8, 2008

So anaconda comes with an assload of its own libraries and binaries, and sometimes this causes problems for me. For instance, I can't just set my PATH to the anaconda/bin folder because then I'm overriding the default path for various tools in a build environment where the versioning is actually pretty important.

The only solution to this is to manually downgrade anaconda packages one at a time to match the system configuration. This isn't easy or convenient. I wish there was a way to tell anaconda that I want it to use and link against the system libraries for everything that it can find

I'm not really asking a question, just venting over some issues that I've been having lately

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

QuarkJets posted:

So anaconda comes with an assload of its own libraries and binaries, and sometimes this causes problems for me. For instance, I can't just set my PATH to the anaconda/bin folder because then I'm overriding the default path for various tools in a build environment where the versioning is actually pretty important.

The only solution to this is to manually downgrade anaconda packages one at a time to match the system configuration. This isn't easy or convenient. I wish there was a way to tell anaconda that I want it to use and link against the system libraries for everything that it can find

I'm not really asking a question, just venting over some issues that I've been having lately

I'm having difficulty picturing your exact problem, but the general idea is why I always use miniconda...have you looked at using that?

QuarkJets
Sep 8, 2008

I have not, but now I will look into it

SurgicalOntologist
Jun 17, 2004

Personally, even though I use miniconda I don't put its main bin folder on my path. I symlink activate and conda into my path, and then never use the root environment. So I don't get conda stuff on my path until I explicitly activate an environment.

QuarkJets
Sep 8, 2008

What if you're deploying code to multiple users on a common system? I usually write a shell wrapper that inline modifies the path and ld_library_path to use anaconda, if it's necessary (such as if my application links against the specific version of pythonxx.so that comes with anaconda).

Things can also become very complicated if your project is using something like cmake to specify your Python area

Boris Galerkin
Dec 17, 2011

I don't understand why I can't harass people online. Seriously, somebody please explain why I shouldn't be allowed to stalk others on social media!
I asked about a pytest plugin to watch my test folders and automatically run a test if the files get modified and someone suggested pytest-xdist. It works great but it has the side effect of making "all tests passed" not green when I'm using the follow (-f) option. It does mark things as red though when things go wrong. Is there a way to make it also do green when good?

Also are there any other neat pytest plugins I should know about? I just started using pytest so this is the first one I've used.

SurgicalOntologist
Jun 17, 2004

QuarkJets posted:

What if you're deploying code to multiple users on a common system? I usually write a shell wrapper that inline modifies the path and ld_library_path to use anaconda, if it's necessary (such as if my application links against the specific version of pythonxx.so that comes with anaconda).

Things can also become very complicated if your project is using something like cmake to specify your Python area

I've only had to face compilation issues with Anaconda a couple of times but I solved it by keeping everything inside Anaconda. Installed all the dependencies as Anaconda packages and then made a conda recipe for the actual compilation. Then you can distribute the precompiled conda package.

Boris Galerkin
Dec 17, 2011

I don't understand why I can't harass people online. Seriously, somebody please explain why I shouldn't be allowed to stalk others on social media!
Why not environment module files? They're pretty neat.

tef
May 30, 2004

-> some l-system crap ->
https://github.com/kennethreitz/pipenv :toot:

Boris Galerkin
Dec 17, 2011

I don't understand why I can't harass people online. Seriously, somebody please explain why I shouldn't be allowed to stalk others on social media!
Why doesn't this work?

https://repl.it/GMLO/1
code:
class Widget(object):
  def __init__(self):
    self._foo1 = 10
    self._foo2 = {'a_key': 20, 'b_key': 30}

  @property
  def foo(self):
    try:
      return self._foo1
    except TypeError:
      return self._foo2

thing = Widget()

print(thing.foo)
>> 10  # as expected

print(thing.foo['a_key']) 
>> TypeError  # raises TypeError but should return 20, from the dict foo2.
Basically I want a dict/container object that has a default return value when I don't give it an index or key or whatever. If I do then I want it to return the value of that key, which internally in my class is saved as a dictionary.

I guess I could just remove the property decorator and it would work, kind of. I don't want to type "thing.foo()", I just want to type "thing.foo". I could make two properties i guess, but I don't want that either. I want a single "foo" property that could return either things.

What the hell is the point of the property anyway? When I google I only see tutorials for making getters and setters and none of that explains to me why I should even bother.

At the moment I use @property on a class method when I want that docstring to show up in the help/pydoc for that class.

Boris Galerkin fucked around with this message at 12:27 on Mar 8, 2017

Dominoes
Sep 20, 2007

You're catching the TypeError before it occurs; ie once you've gotten thing.foo, you have no more error checking, and 10 doesn't have any keys.

@property makes methods look like properties; I think they're for writing Java-style code. I wouldn't use them, since they mask that calculations are being run.

Boris Galerkin posted:

Basically I want a dict/container object that has a default return value when I don't give it an index or key or whatever. If I do then I want it to return the value of that key, which internally in my class is saved as a dictionary.
I'm not sure this is a good idea - you're trying to treat it as two different types of objects based on context. Here's a snippet that does what you ask, although as a function rather than a class.
Python code:
def try_this(my_dict: dict, key) -> Union[dict, int]:
    DEFAULT = 10
    try:
        return my_dict[key]
    except KeyError:
        return DEFAULT
    

my_dict = {'a_key': 20, 'b_key': 30}

print(try_this(my_dict, 'a_key'))  # 20
print(try_this(my_dict, 'not_a_key'))  # 10
Or if you use it a lot:

Python code:
try_my_dict = functools.partial(try_this, my_dict)


try_my_dict('a_key')  # 20
try_my_dict('not_a_key')  # 10
Not sure if this helps, but are you familiar with dict's get method? It'll return a default of your choice if it can't find the key.

Dominoes fucked around with this message at 21:24 on Mar 8, 2017

Eela6
May 25, 2007
Shredded Hen
There are two main reasons for @property.

One is when you want to present a uniform API to your users. If you have a single method that takes only self and will always return the same result for a given object, it's "really" a property. For example, you might lazily compute the perimeter of a 2d shape when asked for, but the users don't need to know whether it's computed during __init__ or when you ask.

Plus, if we only implement a 'getter' for perimeter and not a 'setter', our code won't let us create a rectangle where
P! = 2(WH) well, within the limits of Python floats, anyways...

This helps makes some guarantees about our rectangles being actual rectangles.


The second is as a step in refactoring. Suppose we have a class Frisbee. You initially had a property, Frisbee.curve that was a public attribute. Later on, you implemented an advanced physics and materials simulation; it models the deformation of the Frisbee during its flight! That is, Frisbee.curve is no longer a static property - it can change over time! Clearly, Frisbee.curve needs to be a method that works with your physics simulation. The problem is, all over your codebase and your customers' codebases, there are calls to some_frisbee.curve, not some_frisbee.curve().

Using @property makes the change "invisible" so that the old calling signature will still work.

Excessive use of @property is a warning sign of brittle code, though. At that point you might want to start raising warnings on old API usage that tell the user about your new API that more closely suits how your new code actually works.

if you want to know more, there are sections in 'Effective Python', and a speech by Brett Slatkkn, the author of that book, about this.

Eela6 fucked around with this message at 17:30 on Mar 8, 2017

huhu
Feb 24, 2006
I'm reading about RESTful web services as they relate to Flask. In the introduction, It talks about how you might need to have multiple versions of your website because not everyone can access the new version immediately (i.e. a smartphone app won't be up to the newest version until the user downloads the new version). The smartphone app was the only example given and I'm struggling to understand what else would justify having separate versions of a website with Flask?

Edit: Perhaps a better question, is there a good article/resource that explains RESTful web services well?

huhu fucked around with this message at 19:23 on Mar 8, 2017

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

You might have other sites using your service (if you're providing an API), which aren't really any different from a mobile app. Also I guess it's possible that even if you only have your own frontend accessing it, people might have 'stale' pages loaded that make calls to the old API, and there's a possibility of losing data if they can't talk to the server anymore

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

huhu posted:

I'm reading about RESTful web services as they relate to Flask. In the introduction, It talks about how you might need to have multiple versions of your website because not everyone can access the new version immediately (i.e. a smartphone app won't be up to the newest version until the user downloads the new version). The smartphone app was the only example given and I'm struggling to understand what else would justify having separate versions of a website with Flask?

Edit: Perhaps a better question, is there a good article/resource that explains RESTful web services well?

If you're providing an API for consumption by third parties you need a versioning and deprecation policy.

If you're providing an API for consumption only by yourself, you should probably version it because it's easy to do and will help you in the future if your project grows or you open it up to others or whatever. Any decent REST API will make versioning a simple matter of setting a config variable to True.


It seems a little odd to word it as having different versions of a website...I've never heard of that. Only different versions of the API.

Though, with modern web development, your website is often just another consumer of your API.

QuarkJets
Sep 8, 2008

Thanks for the Miniconda recommendation, it's nice knowing that there is a minimalist version of anaconda out there. But for some reason I'm still having trouble with cmake; it claims to be using the HDF5 libraries and headers in my miniconda area, but it's apparently grabbing my system headers because when I launch my application I get a big gently caress-off warning about a library/header version mismatch (HDF5 at least gives a very thorough warning, as it specifies all of the paths and shows that system headers were used and that miniconda libraries are what is being linked against). This is probably going to require getting a lot more intimate with cmake and/or moc than I'd like

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I switched to PyCharm EAP (basically jetbrains beta program) today just for the hell of it.

The first thing I've noticed is this goddamn amazing "zero latency typing" thing. I've had zero issues with typing latency in PyCharm, but its amazing how great it feels now.

huhu
Feb 24, 2006
I tried to add
code:
@login_required
to my Flask app and now I'm getting an error when accessing those pages with that.

quote:

werkzeug.routing.BuildError: Could not build url for endpoint 'auth.login'. Did you mean 'login' instead?
which led me to this page where it says:

quote:

The default is login but since you don't have a view named 'login'
However, I have the following in my view.py file:
code:
@app.route('/login', methods = ['GET','POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user, remember= False)
            return redirect('/web_viewer')
        flash('Invalid username or password.')
    return render_template('login.html', form=form)
Isn't this a view named login?

Boris Galerkin
Dec 17, 2011

I don't understand why I can't harass people online. Seriously, somebody please explain why I shouldn't be allowed to stalk others on social media!

QuarkJets posted:

Thanks for the Miniconda recommendation, it's nice knowing that there is a minimalist version of anaconda out there. But for some reason I'm still having trouble with cmake; it claims to be using the HDF5 libraries and headers in my miniconda area, but it's apparently grabbing my system headers because when I launch my application I get a big gently caress-off warning about a library/header version mismatch (HDF5 at least gives a very thorough warning, as it specifies all of the paths and shows that system headers were used and that miniconda libraries are what is being linked against). This is probably going to require getting a lot more intimate with cmake and/or moc than I'd like

I have this same problem with cmake and HDF5. I'm not sure why but I've heard from others with similar problems as well.

I was able to "fix" the issue with compiling one thing by just exporting HDF5_ROOT with the cmake command: $ HDF5_ROOT=/path/to/hdf5/root cmake ... Hope that helps.

Dex
May 26, 2006

Quintuple x!!!

Would not escrow again.

VERY MISLEADING!

Eela6 posted:

if you want to know more, there are sections in 'Effective Python', and a speech by Brett Slatkkn, the author of that book, about this.

you're talking about this talk i'm guessing? i liked it

huhu posted:

werkzeug.routing.BuildError: Could not build url for endpoint 'auth.login'. Did you mean 'login' instead?

i haven't used flask in a while but i've had that exact error when using url_for - have you imported login into the auth module there? if you have the same structure as that post you linked but you're not importing login into the __init__, you probably want auth.view.login instead

Space Kablooey
May 6, 2009


huhu posted:

I tried to add
code:
@login_required
to my Flask app and now I'm getting an error when accessing those pages with that.
which led me to this page where it says:

However, I have the following in my view.py file:
*snip*
Isn't this a view named login?

I'm assuming that you are using Flask-Login here, but the gist of my advice should apply to you.

Somewhere in the code, Flask-Login is using this code to redirect your user to your login page:

Python code:
url_for('auth.login')
What that means is:
- Look for the Blueprint named auth and;
- Build a url for the login endpoint in the blueprint.

You are using @app.route, which means that your login endpoint is directly under the application object. There's nothing wrong with this per se, but blueprints are mostly used to organize code, which is a good thing. The biggest drawback is that, compared to the normal Flask way of creating routes, they have a bit of architectural overhead. That said, you have two options here:
1) Create an auth blueprint and put your login route in there;
2) Change Flask-Login's login route in the login manager.

NtotheTC
Dec 31, 2007


Dominoes posted:

Python code:
def try_this(my_dict: dict, key) -> Union[dict, int]:

As an aside, what syntax is this? I've not seen this before in Python.

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

NtotheTC posted:

As an aside, what syntax is this? I've not seen this before in Python.
That's Python type annotations, available since 3.5. It doesn't activate strong typing or anything, it's just a way to add in expected inputs and outputs to method definitions. The part after -> is the method's return value type.

Dominoes
Sep 20, 2007

And I'd like to clarify: That type annotation's not accurate for the function I posted; I got confused part way through about what Boris wanted. Union[dict, int] means it could return either a dict or int. As posted, my example was really just int, or Union[Any, int] if you expect to pass it arbitrary dicts.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

IAmKale posted:

That's Python type annotations, available since 3.5. It doesn't activate strong typing or anything, it's just a way to add in expected inputs and outputs to method definitions. The part after -> is the method's return value type.

And by "expected" he means expected by Python tools. For example IDE's can use it as hints to highlight when you're trying to pass an int to a function expecting a tuple or whatever. Also, you can use MyPy to do static typing on your code.

dougdrums
Feb 25, 2005
CLIENT REQUESTED ELECTRONIC FUNDING RECEIPT (FUNDS NOW)

huhu posted:

I tried to add
code:
@login_required
to my Flask app and now I'm getting an error when accessing those pages with that.

You might have done this, but the login manager class has a field "login_view" that can be set, like
code:
login_manager.login_view = "users.login"
at https://flask-login.readthedocs.io/en/latest/#customizing-the-login-process

I just realized I was using the login extension wrong, I'm glad you asked this ...

I've never done any web-dev before, and despite c# being my goto language I decided to follow https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world up to the point where openid gets involved. I really like using flask, sqlalchemy, the whole bit is really good when I don't really know what I'm doing python-wise. I really like writing python3 though, and it's super loving easy to read other's python3 code.

I just can't handle the runtime type checking though, it makes me real uneasy. I annotate all of my functions and still gently caress everything up all of the time. The best fuckup was when I passed a string into a function that was supposed to take a list of strings and make directories out of them ...

I guess I have two questions for the thread:
- Is there an advantage to annotating my function definitions beyond having some documentation?
- Is there a less heavy handed way to do m:n style threading in python besides using celery/rabbitmq? I'm looking for something like .Net's Task Parallel Library or whatever Go does.


vvv lol now if I can only get this web app to read forum posts for me i'd be solid

dougdrums fucked around with this message at 19:39 on Mar 9, 2017

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

dougdrums posted:

- Is there an advantage to annotating my function definitions beyond having some documentation?

Thermopyle posted:

And by "expected" he means expected by Python tools. For example IDE's can use it as hints to highlight when you're trying to pass an int to a function expecting a tuple or whatever. Also, you can use MyPy to do static typing on your code.

For example, PyCharm uses type annotations to save you from yourself.

Dominoes
Sep 20, 2007

I like being able to get an idea of what the function does by looking at its signature.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

The one thing I don't like about more advanced typing annotations is that they can make the signature too long and noisy and those are the signatures they're most useful with. Syntax highlighting and other IDE features help with that, though.

Python code:
def hi(foo: Union[Callable[str, bool], MyOwnType]], bar: Sequence[Callable[[Union[str, int], Tuple[str, str], bool):

Tigren
Oct 3, 2003

Thermopyle posted:

The one thing I don't like about more advanced typing annotations is that they can make the signature too long and noisy and those are the signatures they're most useful with. Syntax highlighting and other IDE features help with that, though.

Python code:
def hi(foo: Union[Callable[str, bool], MyOwnType]], bar: Sequence[Callable[[Union[str, int], Tuple[str, str], bool):

I know you know better, but one might suggest you could either get rid of the type hints or clean up that signature with a better function name.

QuarkJets
Sep 8, 2008

Dominoes posted:

I like being able to get an idea of what the function does by looking at its signature.

Also makes compiling a function with Numba a good deal easier having the signature right there

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Tigren posted:

I know you know better, but one might suggest you could either get rid of the type hints or clean up that signature with a better function name.

Yes, it was just an example of what can happen.

dougdrums
Feb 25, 2005
CLIENT REQUESTED ELECTRONIC FUNDING RECEIPT (FUNDS NOW)
I've just been doing like:
code:
def hi(
    name : str,
    punc : str):
    print('hello %s%s' % (name, punc))

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

dougdrums posted:

I've just been doing like:
code:
def hi(
    name : str,
    punc : str):
    print('hello %s%s' % (name, punc))

Yeah, that's basically what I do

Adbot
ADBOT LOVES YOU

huhu
Feb 24, 2006

dougdrums posted:

You might have done this, but the login manager class has a field "login_view" that can be set, like
code:
login_manager.login_view = "users.login"
at https://flask-login.readthedocs.io/en/latest/#customizing-the-login-process

I just realized I was using the login extension wrong, I'm glad you asked this ...

I've never done any web-dev before, and despite c# being my goto language I decided to follow https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world up to the point where openid gets involved. I really like using flask, sqlalchemy, the whole bit is really good when I don't really know what I'm doing python-wise. I really like writing python3 though, and it's super loving easy to read other's python3 code.

I just can't handle the runtime type checking though, it makes me real uneasy. I annotate all of my functions and still gently caress everything up all of the time. The best fuckup was when I passed a string into a function that was supposed to take a list of strings and make directories out of them ...

I guess I have two questions for the thread:
- Is there an advantage to annotating my function definitions beyond having some documentation?
- Is there a less heavy handed way to do m:n style threading in python besides using celery/rabbitmq? I'm looking for something like .Net's Task Parallel Library or whatever Go does.


vvv lol now if I can only get this web app to read forum posts for me i'd be solid

Thank you so much.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply