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
punk rebel ecks
Dec 11, 2010

A shitty post? This calls for a dance of deduction.
Thanks for the feedback QuarkJets.

So from what I've gathered, I know how to code, but I just have to learn the alternative ways to do things, and to format my code to be more like "industry standards".

Adbot
ADBOT LOVES YOU

QuarkJets
Sep 8, 2008

You know how to write some code. Programming is a skill, your code is beginnerish. But you're on your way to become a skilled programmer, and with practice you'll get there.

Read this book: https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=pd_lpo_1?pd_rd_i=0132350882&psc=1
It's about Java but its lessons are timeless

punk rebel ecks
Dec 11, 2010

A shitty post? This calls for a dance of deduction.

QuarkJets posted:

You know how to write some code. Programming is a skill, your code is beginnerish. But you're on your way to become a skilled programmer, and with practice you'll get there.

Read this book: https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=pd_lpo_1?pd_rd_i=0132350882&psc=1
It's about Java but its lessons are timeless

How close/far would you say I am for being able to apply and get an entry level job?

CarForumPoster
Jun 26, 2013

⚡POWER⚡

punk rebel ecks posted:

How close/far would you say I am for being able to apply and get an entry level job?

Assuming you have a BS degree in something, you’re at the 50th% of interns who apply with me for a $21/hr job. If you could do the things I mentioned, maybe build a few skills around deploying code such as a flask app to heroku and another to AWS Lambda (both have free tiers) and understood the whys of what quarkjets said you’d be in the 95th%.

To be competitive (top 75th%) for a SW1 (paying >$75k) role you prob want some work experience such as an internship, open source contribs that were meaningful PRs, or paid consulting projects. You’ll def wanna show you can deploy code to prod and work on teams. If you think you’ll got the paid consulting project, register a cheap LLC. You know, you could always join upwork or something too, though that’s much more frustrating for you than just getting an internship.

CarForumPoster fucked around with this message at 02:48 on Apr 24, 2022

Falcon2001
Oct 10, 2004

Eat your hamburgers, Apollo.
Pillbug
Depending on where they are/etc, he could also look for smaller shops that are hiring positions that do coding AND other stuff too, like sysadmin roles or whatever. As long as there's some coding, could be good experience. Although I'm sort of unfamiliar wiht how that tht space looks these days.

punk rebel ecks
Dec 11, 2010

A shitty post? This calls for a dance of deduction.
Okay. I'll work on the things you all said and will come back in this thread some time in the summer.

Hopefully I'll be in the top 75th% by then.

I will focus on:

- Using flake8

- Learning Django (I believe this is an alternative Flask?)

- Working on threading

- Learning list comprehensions

- Learning decorators

- Working on an opensource project

- Creating a gif-afied instructions

CarForumPoster
Jun 26, 2013

⚡POWER⚡

punk rebel ecks posted:

Okay. I'll work on the things you all said and will come back in this thread some time in the summer.

Hopefully I'll be in the top 75th% by then.

I will focus on:

- Using flake8

- Learning Django (I believe this is an alternative Flask?)

- Working on threading

- Learning list comprehensions

- Learning decorators

- Working on an opensource project

- Creating a gif-afied instructions

Some thoughts from when I was starting out:
For me as a newbie I found the ecosystem of Python web frameworks very confusing. Django felt very unfamiliar to me as a newbie.

Threading also has a lot of its own landmines and figuring out why the thing won’t return or waits when it shouldn’t and can be very frustrating when starting out. Did someone suggest learning this to start? I didn’t see it, and would suggest that “I can put Python code on the internet and that code is readable and usable by others” is a far better demonstration of the skills needed in most jobs rather than anything to do with threading. If you wanna thread something fire up AWS lambda lol (I jest but only kinda)

Check out dash, because it’s far easier to get working Python code on the internet and there’s no need to have HTML or JavaScript files to have a useful pokedex. Focus more on “get hello world app on the internet” rather than “learn specific web framework”. Flask and Django are good solutions to different problems, but not they have their own learning curves and landmines.

For me personally, i choose a Python web framework like this:

If I want a single page app like a Pokédex to be up and running in 2 hours on heroku, I choose dash. I highly suggest you start here. Look at my posts ITT as I straight up walk you through deploying Python code to heroku. Dash is built on top of Flask.

If I want a lightweight web framework to build a fairly bespoke thing or an absolutely dead simple API I’d look at flask.

If I want an API to serve JSON from a database, I look at FastAPI unless…

…I want a full on website with a database, authentication, REST API and CMS then I choose Django w/Django CMS and DRF.

CarForumPoster fucked around with this message at 04:34 on Apr 24, 2022

punk rebel ecks
Dec 11, 2010

A shitty post? This calls for a dance of deduction.

CarForumPoster posted:

Some thoughts from when I was starting out:
For me as a newbie I found the ecosystem of Python web frameworks very confusing. Django felt very unfamiliar to me as a newbie.

Threading also has a lot of its own landmines and figuring out why the thing won’t return or waits when it shouldn’t and can be very frustrating when starting out. Did someone suggest learning this to start? I didn’t see it, and would suggest that “I can put Python code on the internet and that code is readable and usable by others” is a far better demonstration of the skills needed in most jobs rather than anything to do with threading. If you wanna thread something fire up AWS lambda lol (I jest but only kinda)

Check out dash, because it’s far easier to get working Python code on the internet and there’s no need to have HTML or JavaScript files to have a useful pokedex. Focus more on “get hello world app on the internet” rather than “learn specific web framework”. Flask and Django are good solutions to different problems, but not they have their own learning curves and landmines.

For me personally, i choose a Python web framework like this:

If I want a single page app like a Pokédex to be up and running in 2 hours on heroku, I choose dash. I highly suggest you start here. Look at my posts ITT as I straight up walk you through deploying Python code to heroku. Dash is built on top of Flask.

If I want a lightweight web framework to build a fairly bespoke thing or an absolutely dead simple API I’d look at flask.

If I want an API to serve JSON from a database, I look at FastAPI unless…

…I want a full on website with a database, authentication, REST API and CMS then I choose Django w/Django CMS and DRF.

Thanks for the advice.

Also, I changed my GitHub username: https://github.com/nkocodes

Finally, I know you said I'm in the 50th% assuming I have a BS degree. I do have a bachelor's from a university, but it's in Psychology. I hope that doesn't push me out of the 50th%.

CarForumPoster
Jun 26, 2013

⚡POWER⚡

punk rebel ecks posted:

bachelor's in Psychology. I hope that doesn't push me out of the 50th%.

You’re competing with CS undergrads, other engineering/math/STEM undergrads, Econ and business major new grads who had undergrad assignments that they used Python for, etc. You gotta be better than them.

If you prove you can do the job with code and work experience on the resume, you interview well and you seem cool to work with, degree won’t matter.

Falcon2001
Oct 10, 2004

Eat your hamburgers, Apollo.
Pillbug
Also, a BS degree is still useful even if it's the same field, because it shows a certain baseline level of 'I can accomplish something concrete." and talks about general knowledge as well.

CarForumPoster
Jun 26, 2013

⚡POWER⚡

Falcon2001 posted:

Also, a BS degree is still useful even if it's the same field, because it shows a certain baseline level of 'I can accomplish something concrete." and talks about general knowledge as well.

Yea while a BA degree says “I failed to find a spouse at the law school’s parties”

i kid

SirPablo
May 1, 2004

Pillbug
List comprehensions are awesome but they can get really wonky to read sometimes. It might be easier just to write your code then go back through and find where you are doing any "for x in range ()" type loops. Those are prime candidates for list comprehension.

QuarkJets
Sep 8, 2008

punk rebel ecks posted:

How close/far would you say I am for being able to apply and get an entry level job?

Depends on the group. For entry level you might be ready right now, it totally depends on who you wind up talking to and what they're looking for. Everything I've recommended is going to boost your chances more and more, because they're all skill-building suggestions and it's good to have experience with a wide array of things that you can point to to demonstrate experience.

If you can get your git project cleaned up a bit, to the point where you have a nice-looking README.md and can actually install the package into a fresh python environment from pypi (e.g. you've published it and gotten the install_requires block down to the bare essentials), then that would be pretty great. "I've developed an app and published it" is something that a lot of people can't say but it's also pretty easy (by which I mean: the publishing part is easy. The real work was in developing the app of course).

Falcon2001
Oct 10, 2004

Eat your hamburgers, Apollo.
Pillbug

SirPablo posted:

List comprehensions are awesome but they can get really wonky to read sometimes. It might be easier just to write your code then go back through and find where you are doing any "for x in range ()" type loops. Those are prime candidates for list comprehension.

I think list comprehensions are one of those very easy to gently caress up 'clever coding' things, but they're also much clearer sometimes, so you have to weigh the balance. Once you get into nesting them it's often much clearer to use a nested If statement instead or something.

punk rebel ecks
Dec 11, 2010

A shitty post? This calls for a dance of deduction.
So I took the advice in this thread and dabbled working around with dash.

I did this tutorial: https://www.geeksforgeeks.org/introduction-to-dash-in-python/

Everything worked as intended, so I decided to make my own little graph from scratch:

Python code:
#import dash
import dash
import dash_core_components
import dash_html_components as html

#declare app
app = dash.Dash()

#create app layout
app.layout = html.Div(children = [
    html.H1("State Population"), #H1 refers to the h1 tag in HTML page
    dash_core_components.Graph(
        id = "population stats",
        figure = {
            'data':[
                {'x' = [1980, 1990, 2000, 2010, 2020],
                 'y' = [23.6, 29.8, 33.9, 37.3, 39.5],
                 'type': 'line',
                 'name': 'California'},
                {'x' = [1980, 1990, 2000, 2010, 2020],
                 'y' = [14.2, 17, 20.9, 25.1, 29.1],
                 'type': 'line',
                 'name': 'Texas'}
            'layout':{
                'title': "California vs Texas Population"                
       }
     }
   )
])

if __name__ == '__main__':
    app.run_server()
This seemed right but I kept getting this traceback error when running it:

code:
 File "c:\Users\nomar\Dropbox\Code\SecondScratchPad.py", line 14
    figure = {
    ^
SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
This SyntaxError made no sense to me, and I couldn't figure out what was wrong since it looked so similar to the template code.

So I went back to the template code in the example:

Python code:
import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()

app.layout = html.Div(children = [
    html.H1("Dash Tutorial"),
    dcc.Graph(
        id = "example",
        figure = {
            "data":[
                {"x":[1,2,3,4,5],
                 "y":[5,4,7,4,8],
                 "type": "line",
                 "name" : "Trucks"},
                {"x":[1,2,3,4,5],
                 "y":[6,3,5,3,7],
                 "type":"bar",
                 "name": "Ships"}
            ],
            "layout":{
                "title": "Basic Dashboard"
            }
        }
    )
])

if __name__ == '__main__':
    app.run_server()
And when I run this time I get this:

code:
Traceback (most recent call last):
  File "c:\Users\nomar\Dropbox\Code\dash.py", line 1, in <module>
    import dash
  File "c:\Users\nomar\Dropbox\Code\dash.py", line 2, in <module>
    import dash_core_components as dcc
  File "C:\Users\nomar\Desktop\Python\lib\site-packages\dash_core_components\__init__.py", line 1, in <module>
    from dash.dcc import *  # noqa: F401, F403, E402
ModuleNotFoundError: No module named 'dash.dcc'; 'dash' is not a package
I mean everything ran fine and it found the module before.

I'm not sure what's going on, can someone please help?

CarForumPoster
Jun 26, 2013

⚡POWER⚡
Dash went through a major version change that changed the API. If your tutorial was for Dash V1 and your installed Dash V2 that may do it.

You’ll find API breaking changes being made with leading number version changes is pretty common in programming. Lot of the similar pitfalls between Django 1 and 2 as well.

punk rebel ecks
Dec 11, 2010

A shitty post? This calls for a dance of deduction.

CarForumPoster posted:

Dash went through a major version change that changed the API. If your tutorial was for Dash V1 and your installed Dash V2 that may do it.

You’ll find API breaking changes being made with leading number version changes is pretty common in programming. Lot of the similar pitfalls between Django 1 and 2 as well.

What tutorial for Dash would you recommend?

The only two I found both center around graphs.

lazerwolf
Dec 22, 2009

Orange and Black

punk rebel ecks posted:

What tutorial for Dash would you recommend?

The only two I found both center around graphs.

I will preface this by saying I don’t have experience with dash (I’m not sure about the quality of their docs), but I would try the official documentation.

An often overlooked skill in a developer is their ability to read the documentation.

Generally the official documentation has a good tutorial to follow.

lazerwolf fucked around with this message at 01:01 on Apr 25, 2022

CarForumPoster
Jun 26, 2013

⚡POWER⚡

punk rebel ecks posted:

What tutorial for Dash would you recommend?

The only two I found both center around graphs.

Id suggest following the official docs and get a hello world app actually deployed.

Falcon2001
Oct 10, 2004

Eat your hamburgers, Apollo.
Pillbug

lazerwolf posted:

I will preface this by saying I don’t have experience with dash (I’m not sure about the quality of their docs), but I would try the official documentation.

An often overlooked skill in a developer is their ability to read the documentation.

Generally the official documentation has a good tutorial to follow.

At the very least, starting with the official documentation is a good way to make sure you're referring to a good source of truth; if you have questions from that, you also end up in a much better place to start googling from once you know the terminology used in that particular project/etc.

punk rebel ecks
Dec 11, 2010

A shitty post? This calls for a dance of deduction.
The official documentation was one of the tutorials I was referring to.

EDIT - Figured out way the tutorial template wasn't working, I named the script "dash" and it was messing things up.

punk rebel ecks fucked around with this message at 05:30 on Apr 25, 2022

CarForumPoster
Jun 26, 2013

⚡POWER⚡

punk rebel ecks posted:

The official documentation was one of the tutorials I was referring to.

EDIT - Figured out way the tutorial template wasn't working, I named the script "dash" and it was messing things up.

Yep that'll do it. We all did stuff like this. Theres a point in learning python where, without thinking about it, you'll not step in these holes. At that point the rate of learning goes up very quickly. Rate of learning vs time is S shaped.

For now, stick to calling files exactly what they do in the tutorial, which I think is app.py for dash. When you make your Procfile to deploy, this will be important once again.

death cob for cutie
Dec 30, 2006

dwarves won't delve no more
too much splatting down on Zot:4

punk rebel ecks posted:

The official documentation was one of the tutorials I was referring to.

EDIT - Figured out way the tutorial template wasn't working, I named the script "dash" and it was messing things up.

I've done lots things like this while teaching - I'll import redirect from Flask, then name a route redirect, and then it all goes to hell. Whoops!

punk rebel ecks posted:

Finally, I know you said I'm in the 50th% assuming I have a BS degree. I do have a bachelor's from a university, but it's in Psychology. I hope that doesn't push me out of the 50th%.

I have a BS in psychology with a minor in sociology! I also got my (more or less useless) certificate from the place I teach at now; about half our instructors have a degree in something that's not CS. The great thing about programming is that, in many cases, nobody really cares about degrees or certificates or whatever - they care about your ability to write code and your ability to communicate about what you've written.

punk rebel ecks posted:

- Learning Django (I believe this is an alternative Flask?)

CFP has talked about this but I want to elaborate on it a bit more - I teach Flask, and I used to teach Django. Of the two, Flask is probably the better to start with - as a micro framework, it's less... opinionated about how it works. A Flask project is an empty Python file that you then add an import of the Flask class to, then you create an instance of that class and do some stuff with it.

To start a Django project, at least the official way of starting it laid out in the Django documentation, you run a few commands from your command prompt that spit out a bunch of boilerplate Python in separate files and directories that, when run, gets everything imported and connected and available. You could, in theory, write it all out by hand in a single file - but it would be tedious and you'd probably gently caress up some stuff, or you'll try to use a Django feature later and realize that it wasn't set up right originally. Django wants you to do things a specific way. For example, you can use something other than the Django ORM to interact with your database - it's Python code, you can do whatever you want whenever you want - but then you lose out on some of the best reasons to use Django. Flask, on the other hand, really just provides a way to take in requests and provide responses. It does provide a little more for you, like it comes with Jinja for templates, but there's nothing saying you can't hand-craft your own responses using whatever template engine you'd like.

We stopped teaching Django because we weren't using any of the cool features that make Django worthwhile, and were burdened by all the expectations it had; it's not great when I have to do a lecture and say things like "we've started this Django project, ignore all these files - but don't delete them, even when they're empty, because then things break". We started teaching Flask because it involves writing more "Python" and less "Python tuned to the structure that Django explicitly asks for".

This is kind of similar to why I argued against teaching Dash when a coworker brought it up - in a sense it is quicker and easier than Flask, but you end up using a lot of complicated stuff that you don't fully understand. Like, Dash uses plotly.js to create real hot-looking charts, but you do it very easily - you don't know the nuts and bolts of it. If you learned Dash fairly well, and put plotly.js on your resume as something you Know, could you use it outside of Dash? This is kind of getting at the concept some other posters were bringing up when they were asking about your code; there's stuff you're doing where you're getting the desired result, but you're not aware of alternatives to what you did, or context for why some choices are good/bad.

punk rebel ecks
Dec 11, 2010

A shitty post? This calls for a dance of deduction.
Good posts everyone.


death cob for cutie posted:

This is kind of similar to why I argued against teaching Dash when a coworker brought it up - in a sense it is quicker and easier than Flask, but you end up using a lot of complicated stuff that you don't fully understand. Like, Dash uses plotly.js to create real hot-looking charts, but you do it very easily - you don't know the nuts and bolts of it. If you learned Dash fairly well, and put plotly.js on your resume as something you Know, could you use it outside of Dash? This is kind of getting at the concept some other posters were bringing up when they were asking about your code; there's stuff you're doing where you're getting the desired result, but you're not aware of alternatives to what you did, or context for why some choices are good/bad.

Is this kind of like how people use an app to create GUI for PyQt instead of coding it “manually” like I do?

punk rebel ecks
Dec 11, 2010

A shitty post? This calls for a dance of deduction.
So I'm doing the official Flask tutorial.

I managed to code the app, but when running it, it wouldn't run.

I then realized that I forgot to create a virtual environment.

It's in the prior page of the tutorial, and being honest I don't have much experience in creating virtual environments.

https://flask.palletsprojects.com/en/2.1.x/tutorial/layout/

I've created the environment but the tutorial doesn't say how to create the folders or save my VSC script to it.



Where would be the best place to look or am I going about this all wrong?

Data Graham
Dec 28, 2009

📈📊🍪😋



Unless I'm misunderstanding -- you don't need to move or copy anything "into" your venv. All it is is an isolated copy of Python that you can run and add libraries to without affecting the Python installed at your OS level, and "activating" it means temporarily changing your environment variables to point to that Python instead of your OS one.

Once you've activated the venv (which you can see by the (venv) prefix on your prompt), you're now using your isolated Python. You can now "pip install -r requirements.txt" to install all your libraries/dependencies for that Python only. And then if you run "python" or your Flask app it will have those libs available.

D34THROW
Jan 29, 2012

RETAIL RETAIL LISTEN TO ME BITCH ABOUT RETAIL
:rant:
I use a git bash terminal inside of VSCode. Virtualenvs gave me trouble at first but then I started getting used to them. Then in my /Users root, I have a .bashrc file that takes care of initializing it for me.

Bash code:
source .venv/Scripts/activate
alias wt='py whitetrac.py'
alias whitetrac='py whitetrac.py'
alias migrate='flask db migrate'
alias shell='flask shell'
alias tests='py tests.py'
alias manager='py manage.py'
alias pygount='pygount --format=summary --suffix=py,html,css'
clear
Activates the venv, then sets up the aliases for ease of use, so I don't have to do py whitetrac.py run --debug or something like that every loving time. Given, I don't use "wt", "tests", or "manager" at all anymore since I shifted all their functionality into parsers and subparsers of whitetrac.py, but still.

I also have my .gitignore/black/flake8 set up to completely ignore the venv folder so that it's not committing and blacking and flake8ing thousands of files that don't quite meet PEP8.

Data Graham
Dec 28, 2009

📈📊🍪😋



And to be clear (looking at that tutorial), what you want is probably like:

code:
$ mkdir flask-tutorial
$ cd flask-tutorial
$ py -3 -m venv venv
$ venv\Scripts\activate
And now you can create the hello.py in the flask-tutorial directory and go from there.

The venv doesn't specifically have to be in that dir for it to work, but if you're trying to follow the tutorial 1:1 it should be in flask-tutorial.

(Functionally your "myproject" dir serves the same purpose as "flask-tutorial", so you've got two levels when you really only need one.)

D34THROW
Jan 29, 2012

RETAIL RETAIL LISTEN TO ME BITCH ABOUT RETAIL
:rant:

punk rebel ecks posted:

So I'm doing the official Flask tutorial.

I managed to code the app, but when running it, it wouldn't run.

I then realized that I forgot to create a virtual environment.

It's in the prior page of the tutorial, and being honest I don't have much experience in creating virtual environments.

https://flask.palletsprojects.com/en/2.1.x/tutorial/layout/

I've created the environment but the tutorial doesn't say how to create the folders or save my VSC script to it.



Where would be the best place to look or am I going about this all wrong?

Also, Miguel Grinberg's Flask tutorial was absolutely fantastic and got me a long way into version 1 of this project. But I would read over the whole thing first and plan ahead for things like Bootstrap, because converting to Bootstrap and blueprints confused the hell out of me and my code at first.

worms butthole guy
Jan 29, 2021

by Fluffdaddy
Hey all, I haven't really messed around with Python much but I have a question...


How do you all deal with switch cases since they don't exist in Python?

I'm trying to do a simple lookup I suppose by a string. If string is x return y etc etc. StackOverflow suggest if..elseif statements but since I have like 50 versions of the string that'd be some messy code.

Is that all we can do with Python?

Thanks!

12 rats tied together
Sep 7, 2006

python has switch case now, but you can also use a dict of string -> function to handle that string

python calls it "match": https://docs.python.org/3/tutorial/controlflow.html#match-statements

D34THROW
Jan 29, 2012

RETAIL RETAIL LISTEN TO ME BITCH ABOUT RETAIL
:rant:

worms butthole guy posted:

Hey all, I haven't really messed around with Python much but I have a question...


How do you all deal with switch cases since they don't exist in Python?

I'm trying to do a simple lookup I suppose by a string. If string is x return y etc etc. StackOverflow suggest if..elseif statements but since I have like 50 versions of the string that'd be some messy code.

Is that all we can do with Python?

Thanks!

I would do it as a dict with strings as keys. Depending on the way you're going about it, something like:'

Python code:
def bar():
    ...
    
def qux():
    ...

funcs = {
    "foo": bar,
    "baz": qux,
    ...
}

def get_the_function(lookup: str):
    return funcs[lookup]
So something like get_the_function("foo")() would execute bar(), etc. I actually use this construct quite often, especially in my main .py for my current project.

Python code:
CLI_ARGS = {
    "run": {
        "debug": {
            "active": True,
            "func": run_debug_server,
            "help": "Run WhiteTrac Web in debug mode.",
            "description": "Running WhiteTrac Web in DEBUG mode...",
        },
        "production": {
            "active": True,
            "func": run_server,
            "help": "Run WhiteTrac Web in production mode.",
            "description": "Running WhiteTrac Web in PRODUCTION mode...",
        },
        "unit-tests": {
            "active": True,
            "func": partial(os.system, "python -m pytest"),
            "help": "Run the unit tests for WhiteTrac.",
            "description": "Running WhiteTrac unit tests...",
        },
...
Calling an argument from the command line invokes the function, my routine uses "active" to decide whether to include the arg, and "help" goes directly to argparse's add_argument to generate the command-line text, "description" as below.

Python code:
def whitetrac(argument):
    """Performs the actual work of doing the function selected at the
    command line.

    Parameters
    ----------
    function
        The function object to use, derived from `CLI_ARGS`.
    """
    function = argument["func"]
    if isinstance(function, partial):
        app.logger.info(argument["description"])
        function()
        app.logger.info("Completed!")
    else:
        if (func := function.__name__) == "run_server":
            app.logger.info(argument["description"])
            function()
        elif func == "run_debug_server":
            app.logger.info(argument["description"])
            function()
        else:
            app.logger.info(argument["description"])
            function()
            app.logger.info("Completed!")
Obviously there's more happening here behind the scenes, but hopefully it illustrates how you can use a dict as a bastard switch case, and use functions as dict items.

D34THROW fucked around with this message at 20:56 on Apr 26, 2022

worms butthole guy
Jan 29, 2021

by Fluffdaddy
I think both will work, thank you for the help! :)

Data Graham
Dec 28, 2009

📈📊🍪😋



Variable function names are an absolute nightmare to debug or reverse-engineer though, just sayin

QuarkJets
Sep 8, 2008

worms butthole guy posted:

Hey all, I haven't really messed around with Python much but I have a question...


How do you all deal with switch cases since they don't exist in Python?

I'm trying to do a simple lookup I suppose by a string. If string is x return y etc etc. StackOverflow suggest if..elseif statements but since I have like 50 versions of the string that'd be some messy code.

Is that all we can do with Python?

Thanks!

I really like dictionary dispatch, it was already mentioned earlier but keep in mind that it's a little different from a traditional switch statement in that you only ever get 1 case, you don't get cascades. It's perfect for lookups though

D34THROW
Jan 29, 2012

RETAIL RETAIL LISTEN TO ME BITCH ABOUT RETAIL
:rant:

QuarkJets posted:

I really like dictionary dispatch, it was already mentioned earlier but keep in mind that it's a little different from a traditional switch statement in that you only ever get 1 case, you don't get cascades. It's perfect for lookups though

Unless the dispatch done by a recursive inner function and you use partial() to pass arguments...maybe?

gently caress did I just write?

punk rebel ecks
Dec 11, 2010

A shitty post? This calls for a dance of deduction.

Data Graham posted:

You can now "pip install -r requirements.txt" to install all your libraries/dependencies for that Python only. And then if you run "python" or your Flask app it will have those libs available.

You lost me here. The tutorial has no "requirements.txt".

Also how do I run my python file from the virtual environment? Navigate to it's folder via the terminal?

I wish there was a way I could do all this from VSC. :(

lazerwolf
Dec 22, 2009

Orange and Black

punk rebel ecks posted:

You lost me here. The tutorial has no "requirements.txt".

Also how do I run my python file from the virtual environment? Navigate to it's folder via the terminal?

I wish there was a way I could do all this from VSC. :(

I use pyenv for virtual environment management. It very simple.

https://github.com/pyenv/pyenv

Follow the readme and you should have a better understanding of what virtualenvs are.

credburn
Jun 22, 2016
A tangled skein of bad opinions, the hottest takes, and the the world's most misinformed nonsense. Do not engage with me, it's useless, and better yet, put me on ignore.
Hey, gang! Can you guys help identify where the problem lies in my code? I've almost got it down.

In this assignment, there is a file called input1.csv -- the online lab thing will input the appropriate name, as well as bunch of other files for the sake of testing. Each one I run into the same problem, which I'll explain in a second.

the contents of input1.csv are:

code:
hello,cat,man,hey,dog,boy,Hello,man,cat,woman,dog,Cat,hey,boy
The assignment wants me to write some code that takes an input and returns the words and their frequencies like so:

code:
hello 1
cat 2
man 2
hey 2
dog 2
boy 2
Hello 1
woman 1
Cat 1
And so here is my code:

code:
import csv

filea = open(input())
fileb = filea.read()
filec = fileb.split(',')
filea.close # I know there are better ways of doing this, but I don't have the with / as thing memorized and I'm trying not to just look this stuff up
bark = {}
for i in filec:
    if i not in bark:
        bark[i] = 1 # goes through the words, adds each new one to the dictionary and gives them a value of 1.
    else:
        bark[i] += 1 # if the word already exists as a key in the dictionary, just add 1 to its value
for k, v in bark.items():
    print(k, v)
But my output looks like this:

code:
hello 1
cat 2
man 2
hey 2
dog 2
boy 1
Hello 1
woman 1
Cat 1
boy
 1
and I can't figure out why. It's always the last one, but I don't know why it wouldn't have appropriately applied added to the the dictionary {bark} in the first for loop. :confused:

I think possibly the very last line of the csv may be interpreted as a newline character or something...? But in the example provided, there is no indication thereof; it just terminates at boy. This being an online environment, it's not without a couple bugs, which makes me really kind of annoyed and always cautious about whether the problem is my code, the software, some limitation of the virtual web-based environment, or even just a flaw in the presentation. But I guess I should err that the error is in my code; it usually is.

credburn fucked around with this message at 05:57 on Apr 27, 2022

Adbot
ADBOT LOVES YOU

QuarkJets
Sep 8, 2008

credburn posted:

Hey, gang! Can you guys help identify where the problem lies in my code? I've almost got it down.

In this assignment, there is a file called input1.csv -- the online lab thing will input the appropriate name, as well as bunch of other files for the sake of testing. Each one I run into the same problem, which I'll explain in a second.

the contents of input1.csv are:

code:
hello,cat,man,hey,dog,boy,Hello,man,cat,woman,dog,Cat,hey,boy
The assignment wants me to write some code that takes an input and returns the words and their frequencies like so:

code:
hello 1
cat 2
man 2
hey 2
dog 2
boy 2
Hello 1
woman 1
Cat 1
And so here is my code:

code:
import csv

filea = open(input())
fileb = filea.read()
filec = fileb.split(',')
filea.close # I know there are better ways of doing this, but I don't have the with / as thing memorized and I'm trying not to just look this stuff up
bark = {}
for i in filec:
    if i not in bark:
        bark[i] = 1 # goes through the words, adds each new one to the dictionary and gives them a value of 1.
    else:
        bark[i] += 1 # if the word already exists as a key in the dictionary, just add 1 to its value
for k, v in bark.items():
    print(k, v)
But my output looks like this:

code:
hello 1
cat 2
man 2
hey 2
dog 2
boy 1
Hello 1
woman 1
Cat 1
boy
 1
and I can't figure out why. It's always the last one, but I don't know why it wouldn't have appropriately applied added to the the dictionary {bark} in the first for loop. :confused:

I think possibly the very last line of the csv may be interpreted as a newline character or something...? But in the example provided, there is no indication thereof; it just terminates at boy. This being an online environment, it's not without a couple bugs, which makes me really kind of annoyed and always cautious about whether the problem is my code, the software, some limitation of the virtual web-based environment, or even just a flaw in the presentation. But I guess I should err that the error is in my code; it usually is.

You've nailed the cause; the last column is actually "boy\n" rather than "boy", so those are identified as distinct. That's why the last line looks like that: print is seeing that newline character and actually printing a new line.

You can very simply remove newline characters (as well as white space) using strip():

Python code:
fileb = filea.read().strip()
Here's the documentation on that string method so that you can read about exactly what it does: https://docs.python.org/3.4/library/stdtypes.html?highlight=strip#str.strip
(newline characters are a kind of whitespace, specifically a new line's worth of it)

Also! I noticed this:
Python code:
filea.close
This should be filea.close(). Or, and I know you mentioned knowing about this already, you could use a context manager. I'm going to point it out anyway, because every time you see one is another opportunity to recall their use later:

Python code:
filename = input()
with open(filename) as filea:
    fileb = filea.read()
filec = fileb.split(',')
bark = {}
...

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