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
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

Dr Subterfuge posted:

This is basically the ideal use case for a deque and more efficient than the general purpose list.

Hell yeah. Love me some data structures

Adbot
ADBOT LOVES YOU

cinci zoo sniper
Mar 15, 2013




Dr Subterfuge posted:

This is basically the ideal use case for a deque and more efficient than the general purpose list.

Whoa, this is neat.

Dr Subterfuge
Aug 31, 2005

TIME TO ROC N' ROLL
I learned about deques from Fluent Python, which I picked up because of reading this thread. So cheers all around. :)

mr_package
Jun 13, 2000
I want to debug a script that isn't throwing any exceptions. How can I get all the info like a breakpoint but with logger or traceback modules, is this possible? e.g. just enable massive amounts of debug logging so I can see how much of the script was executed before the caller bailed (trying to debug something with a lot of moving parts).

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

Dr Subterfuge posted:

I learned about deques from Fluent Python, which I picked up because of reading this thread. So cheers all around. :)

I main Java so I have all the deques. ConcurrentLinkedDeque madam??

Hunt11
Jul 24, 2013

Grimey Drawer
So working with CSV files in pandas and was trying to remember if there was a way to count the number of times certain texts appear in a list and then combine it into one row with the next column listing the number of times said text value appeared.

cinci zoo sniper
Mar 15, 2013




Hunt11 posted:

So working with CSV files in pandas and was trying to remember if there was a way to count the number of times certain texts appear in a list and then combine it into one row with the next column listing the number of times said text value appeared.

df.column.value_counts()

SurgicalOntologist
Jun 17, 2004

Exact match:
Python code:
df.column_with_the_text.value_counts()
Contains text:
Python code:
pd.Series({
    text: df.column_with_the_text.str.contains(text).sum()
    for text in certain_texts
})

CarForumPoster
Jun 26, 2013

⚡POWER⚡
I love you thread and helpful people within.

qkkl
Jul 1, 2013

by FactsAreUseless
Let's say I've defined in my_file.py several enums in an enum class called MyEnum. I now want to use those enums in another file. What works right now is to import the MyEnum class with

code:
from my_file import MyEnum
and then use the enums like

code:
MyEnum.ENUM_1
Is there a way to use the enums by using their names directly without having to prefix them with the MyEnum class name? Basically I'm looking for something similar to a static import in Java because I don't want to type out the class name every time I use an enum.

NtotheTC
Dec 31, 2007


qkkl posted:

Let's say I've defined in my_file.py several enums in an enum class called MyEnum. I now want to use those enums in another file. What works right now is to import the MyEnum class with

code:
from my_file import MyEnum
and then use the enums like

code:
MyEnum.ENUM_1
Is there a way to use the enums by using their names directly without having to prefix them with the MyEnum class name? Basically I'm looking for something similar to a static import in Java because I don't want to type out the class name every time I use an enum.

You could just define the enums at the module level and then import them directly?

code:
from my_file import ENUM_1
What is the purpose of the MyEnum class other than a container for the enums?

E: ignore me Enums are actually a thing now in python, I didn't actually know that

NtotheTC fucked around with this message at 22:15 on Jul 19, 2018

Jose
Jul 24, 2007

Adrian Chiles is a broadcaster and writer
Whats the best library for map data visualisations? Particularly if my datasets have country codes

huhu
Feb 24, 2006

Jose posted:

Whats the best library for map data visualisations? Particularly if my datasets have country codes

Google Maps and Flask?

Edit: you could probably just write a script to spit out an HTML file.

cinci zoo sniper
Mar 15, 2013




Jose posted:

Whats the best library for map data visualisations? Particularly if my datasets have country codes

Plot.ly most likely.

Hedningen
May 4, 2013

Enough sideburns to last a lifetime.
Newbie question: working on optimizing a lovely half sketch I did a year ago as a generic random loot table thing for gaming. Please let me know if I’m going about this the wrong way or if there’s a better way of doing it.

Here’s my current approach:
Function calls random string in an array and stores it. Another function calls previously set string and calls one of several arrays based on that value. These arrays all contain a nearly identical set of strings, with certain strings removed or added based on the first chosen string. The selected array also has a random string called and stored in a new array. Based on called string, function then sets several variables that are tied to the string. Based on one of these values, it then calls for random strings in one to six of five to eleven arrays. The strings called then change one of the stored variables, and all this information is now displayed to the user.

Am I going about this correctly with all these individual arrays? I feel like I’ve overcomplicated this with my lovely programming and “Well, I have a hammer . . .” approach right now.

To explain what it’s for: randomly generating units in a wargame. First array is faction, which then allows or disallows unit types. Second call is to unit type, which has restrictions based off of the result of the faction variable. Third call is equipment, which is limited based on unit type, and where there is a variable number of calls (so if a unit can hold 3 “slots”, then it could make 0-3 calls to a 1-slot array, 0-1 calls to a 2-slot array if 0-1 calls were made to the 1-slot array, or 0-1 calls to the 3-slot array if 0 calls made to 1 and 2 slot arrays, plus three separate 0-slot arrays based on earlier variables can be called). Finally, it recalculates one of the values (unit cost) based on all strings used, generating text for the user.

I’m hoping to expand this a bit so it can generate an entire army at once, so comparing total of unit cost values to a user-set variable is something I’m hoping to eventually add, but I’m not quite there in figuring out how to do that without creating a horrible mess of things. I also think I need to weight the 0-value calls, as I’ve had a couple tests where it managed to generate a weird outlier where it called them far too much, as well as add duplicate handling for a few things.

Linear Zoetrope
Nov 28, 2011

A hero must cook

Dr Subterfuge posted:

This is basically the ideal use case for a deque and more efficient than the general purpose list.

How do they implement this deque? Is it just a general dynamic array except they write the first element so that there are an equal number of unused slots before and after, rather than just after?

necrotic
Aug 2, 2005
I owe my brother big time for this!
Double linked lists with fixed length blocks, with new block data starting in the center of the block.

https://github.com/python/cpython/blob/master/Modules/_collectionsmodule.c

Daviclond
May 20, 2006

Bad post sighted! Firing.

Hedningen posted:

Newbie question: working on optimizing a lovely half sketch I did a year ago as a generic random loot table thing for gaming. Please let me know if I’m going about this the wrong way or if there’s a better way of doing it.

Here’s my current approach:
Function calls random string in an array and stores it. Another function calls previously set string and calls one of several arrays based on that value. These arrays all contain a nearly identical set of strings, with certain strings removed or added based on the first chosen string. The selected array also has a random string called and stored in a new array. Based on called string, function then sets several variables that are tied to the string. Based on one of these values, it then calls for random strings in one to six of five to eleven arrays. The strings called then change one of the stored variables, and all this information is now displayed to the user.

You implementation is a headache to understand for a few reasons (and that's OK):
  • you are misusing the verb "call": a function is called with some arguments. A function may access some variable or attribute. You appear to be referring to both of these scenarios as the function "calling" something else, and it's not.
  • (minor) Python doesn't have arrays, you are probably referring to lists
  • (major) you are using raw values (apparently characters in strings) to represent different kinds of objects (factions, units, equipment). As we are finding out, this makes it hard to reason about your program and maintain/expand it, because you have to constantly translate in your head what each array of strings means

The solution is object-oriented programming and, assuming you've never experienced it before, this is a nice little problem to cut your teeth on.

Hedningen posted:

To explain what its for: randomly generating units in a wargame. First array is faction, which then allows or disallows unit types. Second call is to unit type, which has restrictions based off of the result of the faction variable. Third call is equipment, which is limited based on unit type, and where there is a variable number of calls (so if a unit can hold 3 slots, then it could make 0-3 calls to a 1-slot array, 0-1 calls to a 2-slot array if 0-1 calls were made to the 1-slot array, or 0-1 calls to the 3-slot array if 0 calls made to 1 and 2 slot arrays, plus three separate 0-slot arrays based on earlier variables can be called). Finally, it recalculates one of the values (unit cost) based on all strings used, generating text for the user.

Here's what one approach might look like: we create classes to represent Factions, Units and Equipment. I'll sketch out the latter two. I'll assume the value you want to track depends on both the unit and its equipment.

Python code:
import random


class Equipment(object):
    def __init__(self, name, value):
	""" (this method creates an Equipment object every time you call Equipment()"""
        self.name = name
        self.value = value

    def __repr__(self):
	""" (Python calls this method to get strings representing your object) """
        return f'<{self.name}>'


sword = Equipment('sword', 3)
shield = Equipment('shield', 1)
bow = Equipment('bow', 3)

class Unit(object):
    def __init__(self, name, max_number_items, allowed_items, base_value):
        self.name = name
        self.max_number_items = max_number_items
        self.allowed_items = allowed_items
        self.items = []
        self.base_value = base_value

        self.select_random_equipment()
        self.total_value = self.base_value + self.calculate_items_value()

    def select_random_equipment(self):
        """ gives the unit up to max_number_items of random items """
        number_items = random.randint(0, self.max_number_items)
        for _ in range(number_items):
            self.items.append(random.choice(self.allowed_items))

    def calculate_items_value(self):
        result = 0
        for item in self.items:
            result += item.value
        return result

    def __repr__(self):
        return f'<{self.name}, value: {self.total_value}, items: {self.items}>'


class Swordsman(Unit):
    def __init__(self):
        super().__init__('swordsman', 2, [sword, shield], 10)


class Archer(Unit):
    def __init__(self):
        super().__init__('archer', 1, [bow], 6)
Hopefully that gives the general idea: we've got a whole load of common code in the Unit class, and then things like Swordsman and Archer inherit all of that from Unit and set their own values for e.g. item pools. You would then have a similar approach for Factions: a bunch of logic for selecting random unit types from a list of allowed Units that each faction can contain (e.g. [Swordsman, Archer]). I haven't put in the logic where different numbers of allowable items cause them to be drawn from different pools, that's a Fun Problem, but you can expand from this.

So if we do:

Python code:
my_army = [Swordsman(), Swordsman(), Archer()]
print(my_army)
We get back [<swordsman, value: 14, items: [<sword>, <shield>]>, <swordsman, value: 13, items: [<sword>]>, <archer, value: 9, items: [<bow>]>]

The design isn't perfect, and maybe some OO wizard here can make some suggestions, but it's already much easier to conceptualise than a bunch of arrays of strings.

Daviclond fucked around with this message at 22:27 on Jul 23, 2018

SurgicalOntologist
Jun 17, 2004

SQLAlchemy question.

I can't get a hybrid method to work. Here's the test:

Python code:
def test_player_most_recent_team(db, tb, patriots, tb_game):
    assert tb.most_recent_team() is patriots

    db.add(tb_game)
    db.commit()
    assert db.query(models.Player).filter(models.Player.most_recent_team() == patriots).one() is tb
The first line tests the instance method, the second tests the class expression. The first line works, the second gets
code:
sqlalchemy.exc.ArgumentError: Object Team('New England Patriots') is not legal as a SQL literal value
Pretty sure my problem is with the test (well, the method could be wrong too but I'm definitely not testing it right)... what's the proper way to filter based on a hybrid method? Or am I doing it wrong and it should be some kind of relationship?

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

Hedningen posted:

Newbie question: working on optimizing a lovely half sketch I did a year ago as a generic random loot table thing for gaming. Please let me know if I’m going about this the wrong way or if there’s a better way of doing it.

Here’s my current approach:
Function calls random string in an array and stores it. Another function calls previously set string and calls one of several arrays based on that value. These arrays all contain a nearly identical set of strings, with certain strings removed or added based on the first chosen string. The selected array also has a random string called and stored in a new array. Based on called string, function then sets several variables that are tied to the string. Based on one of these values, it then calls for random strings in one to six of five to eleven arrays. The strings called then change one of the stored variables, and all this information is now displayed to the user.

Am I going about this correctly with all these individual arrays? I feel like I’ve overcomplicated this with my lovely programming and “Well, I have a hammer . . .” approach right now.

To explain what it’s for: randomly generating units in a wargame. First array is faction, which then allows or disallows unit types. Second call is to unit type, which has restrictions based off of the result of the faction variable. Third call is equipment, which is limited based on unit type, and where there is a variable number of calls (so if a unit can hold 3 “slots”, then it could make 0-3 calls to a 1-slot array, 0-1 calls to a 2-slot array if 0-1 calls were made to the 1-slot array, or 0-1 calls to the 3-slot array if 0 calls made to 1 and 2 slot arrays, plus three separate 0-slot arrays based on earlier variables can be called). Finally, it recalculates one of the values (unit cost) based on all strings used, generating text for the user.

I’m hoping to expand this a bit so it can generate an entire army at once, so comparing total of unit cost values to a user-set variable is something I’m hoping to eventually add, but I’m not quite there in figuring out how to do that without creating a horrible mess of things. I also think I need to weight the 0-value calls, as I’ve had a couple tests where it managed to generate a weird outlier where it called them far too much, as well as add duplicate handling for a few things.

This was kinda hard to follow - which is the whole problem, right! I think you need to structure this in a way that resembles your actual game design, instead of juggling arrays. Let me see if I got this right:

  • You have a bunch of units, each with a different number of slots
  • You have a bunch of factions, each allowing a different set of units
  • You have a bunch of equipment, each taking up a certain number of slots, and having a cost

I guess the most Pythonic way would be to use dictionaries? Something like

Python code:
units = {
    "Car": 1,
    "Boat": 2,
    "Big Boat": 3
}

factions = {
    "Good guys": ("Car", "Boat"),
    "Baddies": ("Car", "Boat"), 
    "Pirates": ("Boat", "Big Boat")
}

equipment_by_size = {
    1: ("Pew pew gun", "Bucket seat", "Parrot"),
    2: ("Water cannon", "Large parrot")
    3: ("Parrot King")
}
But if you start adding costs to the equipment, those lists (well I used tuples but whatever) can't just be names, you'll need a list of data structures with a Name and a Cost. You could use dictionaries again, so you're nesting them, but probably something like a namedtuple would be easier to work with

Python code:
from collections import namedtuple
Item = namedtuple('Item', ['name', 'cost', 'size'])

equipment = {
    "PEW PEW" = Item("Pew Pew Gun", 100, size=1), # you can use named arguments if it's clearer, like this
    "BUCKET SEAT" = Item("Bucket seat", 50, 1),
    "PARROT" = Item("Parrot", 1000000, 1),
    "PARROT KING" = Item("Parrot King", 666, 3)
    ...
}
Now you have a pretty neat set of items, with attributes on each (and you can add more easily too). You can implement the rest of the stuff like this

Python code:
Unit = namedtuple('Unit', ['name', 'cost', 'slots'])
units = {
    "CAR": Unit("Car", 100, 1),
    "BOAT": Unit("Boat", 200, 2)
}

Faction = namedtuple('Faction', ['name', 'allowed_units'])
factions = {
    "GOOD GUYS": Faction("Good guys", set("CAR", "BOAT")),
    "PIRATES": Faction("Pirates", set("BOAT", "BIG BOAT"))
}
Few things to mention with this
  • I'm using sets for each faction's unit types, since you don't want repeats like you could have with lists. Using the right data structure for the job basically
  • In those sets, it's just storing the lookup keys for different unit types - you'd need to look up the actual unit object each time. It would be more efficient to have a set like set(units["CAR"], units["BOAT"]) where it's looking them up at definition time, and adding the actual unit object to the set. Then you can just work with them instead of doing lookups every time. This is a design decision though
  • Unit defines the number of slots on each unit, since that's info you'd like to access when you have the unit object itself. But if you want to e.g. find all the 2-slot units, you'd need to iterate over the whole units dictionary, filtering on the ones with slots=2. To make this faster, you might want to build a lookup dictionary when your program starts - just using the info you've defined here, building a dictionary of num_slots -> list_of_units, iterating over all the units and popping each one in the appropriate list. Since this runs automatically, if you ever make changes you just work on the definitions, and they'll end up in the right place in the lookup. Don't define things in multiple places if you can help it
  • You'd probably want to do the same for your equipment too, lookup by number of slots


This isn't necessarily the best way, or even the way I'd do it (I'd prefer something like daviclond's solution because it's more familiar) but hopefully it's a start point, give you some ideas about organisation and rounding up your data into something easier to work with. Also someone tell me if this is bad, I've tried to use the more Pythony OO-lite approach with dicts and all that, but it always rubs me up the wrong way. I don't like referencing variables using typoable strings, I always want to make them global constants - define all the Units on the top level etc, then make sets of { CAR, BOAT } instead of { "CAR", "BOAT" } or whatever

Dead Goon
Dec 13, 2002

No Obvious Flaws



I am a total newbie and slowly working my way through Automate The Boring Stuff With Python. I am understanding the concepts and see wht is going on, but I am totally failing when it comes to the practice projects from Chapter 3 onwards. Once it gets to actually having to think like a coder and put together a program I completely blank and end up searching for a solution online. I can look at that solution and understand what and why, but I just can't do it myself.

Would a book like Think Python help with beginning to think like a coder? Are there any other books out there to help with the thinking and logic side of coding?

The Fool
Oct 16, 2003


Forget about Python specifically for a little bit and try sketching the problem out on paper first.

In plain language, write out the logic needed to solve the problem step by step, be as granular as possible.

Then you can start replacing your logical steps with actual Python code.

Dead Goon
Dec 13, 2002

No Obvious Flaws



The Fool posted:

Forget about Python specifically for a little bit and try sketching the problem out on paper first.

In plain language, write out the logic needed to solve the problem step by step, be as granular as possible.

Then you can start replacing your logical steps with actual Python code.

Great advice, thank you!

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

Paper is the best. Get away from the computer too, if you can

Dead Goon
Dec 13, 2002

No Obvious Flaws



Thanks both, I do find sitting in front of my computer, IDE open and just feeling completely blank. I'll go somewhere else with a pad of paper and work through it.

Hedningen
May 4, 2013

Enough sideburns to last a lifetime.
Thank you all for the help! I’ve gotten it into a much more OO fashion right now: everything is now in classes and subclasses, which has made it much easier to debug and expand! I’ll keep tinkering and come back later when I inevitably hit another wall.

As far as methods: because there’s a relatively long list of equipment and a unit was more likely to be able to use something than not, I went with adding all equipment into a list and then comparing to forbidden equipment values that each subclass of unit has, as it seemed like a better fit for what I needed. Is this a good approach? I feel like it’s better as far as maintainability and avoiding repetition.

Daviclond
May 20, 2006

Bad post sighted! Firing.

Hedningen posted:

As far as methods: because there’s a relatively long list of equipment and a unit was more likely to be able to use something than not, I went with adding all equipment into a list and then comparing to forbidden equipment values that each subclass of unit has, as it seemed like a better fit for what I needed. Is this a good approach? I feel like it’s better as far as maintainability and avoiding repetition.

Yeah I don't see anything wrong with the blacklist approach. I second baka kaba's suggestion of using sets instead of lists, though. It's the natural data structure if your items are unique and gives you a really nice overloaded subtract operator:

Python code:
>>> all_equipment = {sword, shield, bow}
>>> blacklist = {bow}
>>> all_equipment - blacklist
{<sword>, <shield>}

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

Another thing you could try is a "standard equipment" collection, that way you can define sets of the base stuff plus whatever individual items you want

Python code:
standard_equipment = { gun, bigger_gun, funny_hat }
good_guys_equipment = standard_equipment | { power_halo }
bad_guys_equipment = standard_equipment | { evil_hat, normal_hat }
# the | is the union operator - basically it combines two sets and gives you a -new- one containing everything 
so that way you're describing stuff in terms of groups of things plus some specifics. It might be easier to work with since you're thinking in terms of who's allowed to use what, and not who isn't - it depends on the mental model you're using though, whichever works!

The other nice thing about this approach is it might help to group stuff in other logical ways, so you can make collections of hats and shoes, or ranged and melee weapons, and define a unit (or whatever) as a recipe - add together all the collections of things you want it to use (maybe omitting some depending on the faction) and any specifics on top of that. With a good naming scheme it might make your definitions super readable. It might also be over-engineering things, so y'know - use yr judgement!

Oh also frozenset is the real correct structure - a set you can't modify once it's defined. Since these are fixed definitions, it's safer to make sure you can't accidentally change them in your code and end up with subtle bugs

baka kaba fucked around with this message at 01:42 on Jul 24, 2018

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!

Dead Goon posted:

Thanks both, I do find sitting in front of my computer, IDE open and just feeling completely blank. I'll go somewhere else with a pad of paper and work through it.

And if sketching out routines with words don't work for you because it's not your style, then go hog wild with drawing flowcharts. It's kinda all the same thing.

Ellie Crabcakes
Feb 1, 2008

Stop emailing my boyfriend Gay Crungus

SurgicalOntologist posted:

SQLAlchemy question.

I can't get a hybrid method to work. Here's the test:

Python code:
def test_player_most_recent_team(db, tb, patriots, tb_game):
    assert tb.most_recent_team() is patriots

    db.add(tb_game)
    db.commit()
    assert db.query(models.Player).filter(models.Player.most_recent_team() == patriots).one() is tb
The first line tests the instance method, the second tests the class expression. The first line works, the second gets
code:
sqlalchemy.exc.ArgumentError: Object Team('New England Patriots') is not legal as a SQL literal value
Pretty sure my problem is with the test (well, the method could be wrong too but I'm definitely not testing it right)... what's the proper way to filter based on a hybrid method? Or am I doing it wrong and it should be some kind of relationship?
It looks like it already is a relationship.

Maybe something like
code:
assert db.query(models.Player).filter(models.Player.most_recent_team_id == patriots.id).one() is tb

NtotheTC
Dec 31, 2007


Anyone have any experience with using Poetry for python projects? I recently moved over to using pipenv for everything (still a huge improvement over virtualenvwrapper or vex or whatever was used beforehand) only to learn about Poetry the other day and looking at it it does seem to have massive advantages despite being newer.

Reformed Pissboy
Nov 6, 2003

Sometime in the last few releases, PyCharm's Structure view has stopped automatically updating when I switch tabs/documents and now I need to click inside it to get the list of methods etc. in the current open module. And when you click inside it, if you accidentally click on a symbol name from the previous doc, it will take you back there to the previous doc!! And then load the Structure list from the doc you actually wanted!!! I hate it and is there a way to change this please.

SurgicalOntologist
Jun 17, 2004

Peeny Cheez posted:

It looks like it already is a relationship.

Maybe something like
code:
assert db.query(models.Player).filter(models.Player.most_recent_team_id == patriots.id).one() is tb

Nah, it's not a relationship. It's a hybrid method, a function that is implemented once as an instance method and once as a SQL expression classmethod. (In my DB structure I don't actually track the roster status of each player over time, just their game stats, so to see a player's current team the best way is to find the team they most recently appeared in a game for). But I'm thinking it could work better as a viewonly relationship with a custom join...

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

Reformed Pissboy posted:

Sometime in the last few releases, PyCharm's Structure view has stopped automatically updating when I switch tabs/documents and now I need to click inside it to get the list of methods etc. in the current open module. And when you click inside it, if you accidentally click on a symbol name from the previous doc, it will take you back there to the previous doc!! And then load the Structure list from the doc you actually wanted!!! I hate it and is there a way to change this please.

Dunno but (I'm going off IntelliJ here) is there an option at the top of the tool window to automatically switch one view when you navigate in another? Icon looks like a little gun sight, you probably want it working one way but not the other (structure window following the editor one)

Thermopyle
Jul 1, 2003

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

NtotheTC posted:

Anyone have any experience with using Poetry for python projects? I recently moved over to using pipenv for everything (still a huge improvement over virtualenvwrapper or vex or whatever was used beforehand) only to learn about Poetry the other day and looking at it it does seem to have massive advantages despite being newer.

Massive advantages like what?

I've stayed away from it because I don't necessarily want the best package manager thingy, I want one good enough package manager thingy to become super common and widespread...and that's most likely going to be pipenv.

mr_package
Jun 13, 2000
After this 2018.2 update my projects are no longer showing added/modified/deleted in the gutter. Is there a hidden setting I need to re-enable? Maybe I should delete all settings / preferences and try restarting fresh?

edit: Pycharm

mr_package fucked around with this message at 18:36 on Jul 27, 2018

Thermopyle
Jul 1, 2003

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

mr_package posted:

After this 2018.2 update my projects are no longer showing added/modified/deleted in the gutter. Is there a hidden setting I need to re-enable? Maybe I should delete all settings / preferences and try restarting fresh?

edit: Pycharm

Sometimes after an update I have to do File > Invalidate Caches / Restart...

IIRC, this empties the IDE's Local History (which is different from your VCS history), so make sure you aren't dependent upon that.

mr_package
Jun 13, 2000
That didn't do it so I deleted all the settings as per https://www.jetbrains.com/help/pycharm/2018.2/project-and-ide-settings.html (which was stupid, I should have backed them up, because I'm never going to remember the 2 or 3 useful changes I made to PyCharm's 10 trillion settings) but no change. I'm going to assume bug on OSX for now. Downgraded back to 2018.1.4 because I really rely on this feature quite a bit actually.

Krakkles
May 5, 2003

I'm doing this in python, so I'm asking here, but this might also be a more generic "good / bad programming practices" question, as well.

I have a function that uses selenium to manipulate, and BeautifulSoup to analyze, a webpage with several buttons on it. Is it better to build the function assuming that the selenium browser object will already have been created, or to explicitly pass it to the function?

It hasn't mattered so far, but I figure it's better to learn these things before I form bad habits.

(If it matters, there are multiple functions that I'm working on creating, but the particular one that gave rise to this takes as input a list indicating the desired state of each of 8 buttons, and returns a list of the previous state of these buttons/whether it was changed.)

Adbot
ADBOT LOVES YOU

Thermopyle
Jul 1, 2003

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

Krakkles posted:

I'm doing this in python, so I'm asking here, but this might also be a more generic "good / bad programming practices" question, as well.

I have a function that uses selenium to manipulate, and BeautifulSoup to analyze, a webpage with several buttons on it. Is it better to build the function assuming that the selenium browser object will already have been created, or to explicitly pass it to the function?

It hasn't mattered so far, but I figure it's better to learn these things before I form bad habits.

(If it matters, there are multiple functions that I'm working on creating, but the particular one that gave rise to this takes as input a list indicating the desired state of each of 8 buttons, and returns a list of the previous state of these buttons/whether it was changed.)

By "assuming that the selenium browser object will already have been created" I think you mean a global object. We generally try to avoid global objects.

Pass it to your functions.

Even better think about if what you really need is a class.

Maybe a initialize_the_browser method on the class and then your methods can just reference self.browser. Or you can make self.browser a property and initialize it on first access.

Sometimes its better to just have a module of functions that take the browser object as an argument.

Or maybe you can just say gently caress it and make global browser object.

Kind of depends on how Serious Business your program is.

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