« first day (3538 days earlier)      last day (1393 days later) » 

12:07 AM
<local time> cabbage all
anyone remember how to turn off developer story? is it just not turn off-able anymore?
ah, nevermind you can just make it private - there is no way to delete it
 
12:27 AM
Is there a preferred way to document/docstring a metaclass? It's kinda it's own documentation? I've got a Database metaclass that I'm using to define the API for the subclasses which will provide the database via JSON/text files, sqlite, postgres etc.
Or are the @abc.abstractmethods and their docstrings kinda self-documented?, in a sense?
 
I just use decorators (the @) with the odd comment where needed (usually for my future self who will undoubtedly argue with my approach)
 
help(Database) shows all the methods/their docstrings. Database.__doc__ only shows the Database class docstring, not the method names or their docstrings.
 
if I'm using a metaclass as part of an API: the methods should be pretty self-explanitory or I start to rethink my approach
To be fair, if I'm using a metaclass at all - I'm going to be rethinking my approach a few times on general principle ;)
 
@LinkBerest Amen, that is partly why I am here. When I was young and naiive, I implemented persistence with text files in this quick and dirty app I built for my wife, so I've spent many hours refactoring the persistence into this database object.
@LinkBerest What's the potential pain point? Or is a simple baseclass often better than a metaclass? My thought was that I can't implement a FancyNewDatabase(Database) and neglect to implement a rarely used method (finding this out much later), because it would error on instantiation?
 
12:49 AM
with metaclasses? I just run into many issues where a simple dataclass would have worked. I do use them when dynamic programming is needed which happens sometimes with APIs - like adding to a model or refactoring a class's attributes (typically with a database the schema is set so the model doesn't change enough to warrant a meta)
my biggest pain point with meta classes would be my code starts looking like Jython after a while - and that's just ugly (not to mention it give me nightmares when I try to maintain it later)
@toonarmycaptain I mean with a normal class it will only do this if you use raise NotImplementedError("you cannot use this method here!") within the @abstractmethod (otherwise it should just silently ignore that method...well if the class is an Abstract too)
 
Ah. Fair enough.
I'll be using SQL alchemy at some point, I'm sure, but for right now I'm going to implement all the queries the app will use by hand under the necessary methods, which might be unwise, but I'll surely learn a thing or two.
 
1:10 AM
cbg
btw, what is a good test to write for loading an image via PIL
i was trying out tdd for a project and i realized the file loading stuff is a bit weird to use the unittest library and assert with
 
@toonarmycaptain hehe... might
I remember using those words once in a similar (in my case having to do with graphing) situation - have fun :) ;)
 
@LinkBerest Well the idea here is more learning than production wisdom. Although the idea that one would implement an interface between app and database to facilitate the implementation of different database backends (or GUI frontends etc) isn't that insane, is it?
 
nah, I do that a lot when dealing with data flows (SQLite, H2....hate H2, MySQL, and even flat files) - I just use standard Abstraction with SQLAlchemy methods for the most part (the actually kicker in my case is the cleaning methods - most of the loading is just onto MongoDB afterwards and pretty simple). Its also a good learning experience
it just reminds me of something I literally just finished cleaning up dealing with graphing things where I was like "hmm...building a D3 wrapper for these dashboards based on the output of my python apps shouldn't be too hard" ....... ;)
@Skyler typically if you want to do file tests you use a mock
3
A: writing a pytest function to check outputting to a file in python?

Enrico M.Suppose you have this "amazing" piece of software in a file called main.py: """ main.py """ def write_to_file(text): with open("output.txt", "w") as h: h.write(text) if __name__ == "__main__": write_to_file("Every great dream begins with a dreamer.") To test the write_to_file...

@toonarmycaptain fyi - if I sound a bit more cranky then usual; I apologize. I spent all evening doing DevOps clean-up and I think its affecting my brain
 
1:32 AM
@Skyler I would use a mock of open, or the function calling open, but pytest has a tmpdir fixture that lets you interact with a mock filesystem/files, which if you need it, you can use build files on disk to run tests against.
 
hmm, ok
 
@LinkBerest You're fine. :)
 
@Skyler my link is a unitest example, I tend to use pytest's tempdir myself (as toon pointed out) - example question using pytest
 
yea, that mock_open stuff seemed simple enough to implement and tempdir sounds like a nice thing to keep in mind since I'm already using unittest mainly atm
 
1:50 AM
I could be wrong, but it would make sense if pytest cached the fixture between tests, and maybe kept it in memory rather than on disk, which might be faster than actually using a physical file.
 
yea, I do a bit of testing on logic for preparing a queue of files in an app, for that something like that might make sense, but I think a mock_open is good for just testing operations on files
 
*tests using parametrize, anyway.
 
I'm pretty sure fixtures are cached
nevermind (saw your second part): yeah its only one at a time so parametrization kinda messes it up
 
Idk, I'd imagine some optimisations are possible, whether pytest chooses to implement them, or how difficult they'd be to implement while ensuring tests are 100% insulated from eachother, might be another matter. Sometimes I just need a couple of directories to exist...I'd hope that's cached or purely im memory rather than physically built, but maybe not.
 
you could probably play around with the scope to load all the mock files at the start (in 'session') thereby allowing them to be cached and passed....would depend a lot on the use-case
 
2:09 AM
@LinkBerest In both unittest/pytest, I believe you can have a setup method per class/module, and ditto with fixtures. Of course if any test modifies any of your files inadvertently, you may have issues...
 
@toonarmycaptain yeah, it be possible to load them all (I'm just not sure if the instances would cache....have to play around with it sometime and see)
 
@LinkBerest Do you have a solution for enforcing attribute existence on subclasses? Currently I've got a abc.ABCMeta that checks for existence of attrs from a list of strings, since @abstractattribute is depreciated in favour of @abstractproperty and I don't want to have to define endless set/get/del methods, but that's not the most elegant, compared to @abstractmethod.
 
@toonarmycaptain if its a lot of attributes you can use a mixin
 
Currently I have:
class ABCMetaEnforcedAttrs(abc.ABCMeta):
    required_attributes: List[str] = []

    def __call__(cls, *args, **kwargs):
        obj = super(ABCMetaEnforcedAttrs, cls).__call__(*args, **kwargs)
        for attr_name in obj.required_attributes:
            if not hasattr(obj, attr_name):
                raise TypeError(f"Can't instantiate abstract class {type(obj)} without required attribute {attr_name}.")
        return obj
And my abc: class Database(abc.ABC, metaclass=ABCMetaEnforcedAttrs):
 
2:26 AM
yeah, that's pretty close to a mixin :)
 
@LinkBerest mixin is where you inherit both from your base class and the mixin, right?
My only complaint (and I don't think a mixin solves this) is that I can't delete the attr required_attributes from the subclasses, AFAICT, at least without removing it from the ABC as well, which isn't what I want.
 
2:43 AM
oh, with hiding it you could use a mixin but I don't think there really is an "elegant" way (you may be able to use delattr to "remove it" - or set it to None at least - that's something I always have to play around with for a bit)
This is where I tend to get in the territory of "I'm breaking the subclassing concept using meta-classes - is this a good idea?" (the question also has a similar approach to what your using)
 
@LinkBerest You can assign another value to it, but that won't stop it being accessible, appearing in .__dict__ or .__doc__ etc. Which is fine, just I don't really want it in my subclass` autocomplete...
 
yeah, that what I meant by "hiding" :)
whenever I talk about inheritance in Python I feel like all SOLID concepts need air quotes ;) :P :)
 
2:59 AM
@LinkBerest lol
 
Also, for anyone who like me was annoyed at the removal of research from the downvote tooltip (or just the new giant tooltips themselves): that feature is being rolled back
 
 
2 hours later…
5:14 AM
stackoverflow.com/questions/62527692/… I do not like it when OP makes zero effort in trying to understand anything.
 
6:10 AM
Is there a way to restrict the amount of memory usage of a Python program, say to 1GB max?
 
21
Q: How to limit memory usage within a python process

ArneI run Python 2.7 on a Linux machine with 16GB Ram and 64 bit OS. A python script I wrote can load too much data into memory, which slows the machine down to the point where I cannot even kill the process any more. While I can limit memory by calling: ulimit -v 12000000 in my shell before runn...

5
Q: Limit python script RAM usage in Windows

BestRMy program can allocate suddenly a lot of RAM based on usage. I want to limit the RAM it can take from the system. I saw here: Limit RAM usage to python program But it works only for Unix. Any solution for Windows?

 
I meant is there is a linux command that does that
 
did you even read the first answer I linked?
 
yup, ulimit i read that
but that would restrict the number of fd, i mean does it apply to a single python program?
thats my more specific question i guess
does ulimit work for a single process limiting its memory?
 
woah, blast from the past
 
6:17 AM
26
Q: setting ulimit on a running process

Lorenzo PistoneI launched a server application and I want to run it for a long time for testing purpose. Unfortunately, I forgot to set before ulimit -c unlimited to catch an eventual crash and inspect it. Is there something I can do?

like literally putting "set ulimit on a running process" into your favorite search engine will turn up threads like that
@Arne yeah it is always funny when you come across your own threads on SO when you don't expect it
 
@kauray to quote the very good answer I got back then:
> [...] The second thing to note is that ulimit/setrlimit only affects the current process and its future children.
 
oh, thanks to both
 
6:53 AM
so logging converts \t into the tab character on my machine but on the actual server logs it appears as the unicode 2020-06-23 06:25:50,103: #011full title:where #011 is supposed to be \t.
I feel this might be some encoding issue—is there a way to edit the encoding without defining my own logger and handler?
 
3
Q: Why does rsyslog replace tabs with #011?

SamriangI am using rsyslog to collect nginx logs. All looks good except the replacing usual tabs with '#011' text. Example of corrupted output: 217.118.93.88#0111473674833.412#0114418687#011... How it should look: 217.118.93.88 1473674833.412 4418687 ... Why it is happens and how to disab...

otherwise please be more explicit by what you mean by "logging" and "server logs", because Python does not have an encoding that produce # prefixed output afaik.
 
ah thank you, does this mean the backend provider is using rsyslog maybe and they convert it?
I am using the logging library and the backend is hosted on pythonanywhere so logs there
 
7:10 AM
Maybe? I don't know what or how your application is set up or how pythonanywhere manage logging/display - I don't trust any hosting solutions that doesn't provide shell level access to the environment. If they inject a syslog handler and then provide logging output through that to you then that might be the source of the issue, but if you are seeing this issue by accessing the raw log file produced with the standard logging file handler, on the server itself, then this would be a real issue.
 
i am trying to convert this Apr-18 month year to data type other then character . please guide to convert this . tryed with code df['month_year'] = df['date_column'].apply(lambda x: x.strftime('%b-%y')) . but still data type is showing object
 
 
1 hour later…
8:23 AM
can we add list as row in pandas dataframe column? like [0.234,0.345,0.345] as row for every row in column in this format without breaking the values of list and saving individually in row or column.
 
8:37 AM
@Kevin Optional assignment is useful when some other code calculates/assigns the value. That may be some un-annotatable statement, such as a for loop, or some loosely related code, such as __init__ setting a value for a field annotated on the class.
 
 
3 hours later…
11:26 AM
hey guys do you need to reset environment variables in powershell everyday you reopen it?
 
11:38 AM
@NabiShaikh datetime.strptime('Apr-18', '%b-%d') will give you that format of string as a date but it will auto give you a year of 1900. Does this answer your question?
 
11:52 AM
@Kwsswart no. what makes you think you have to?
 
Every day? No. Every time? Depends on how you set them
 
just did it yesterday through $env:DATABASE_URL="url to db" and today had to do it again before working on project aswell have to reset FLASK_APP="application.py"
 
environment variables lifetime ends with the life of the process where they were defined. usually that's when you close the window where you wrote that in
assuming your terminal uses bash, there is a file at ~/.bashrc that is executed before you start a bash session which you can use to define environment variables that should always exist. see unix.stackexchange.com/questions/129143/…
 
@Kwsswart Do you mean that you closed the previous powershell session, and now have to set them again in a new session?
 
12:07 PM
ive been using visualstudio code and I left it yesterday at a point shut down when restarting it then need to redefine variables before reopening?
 
12:29 PM
@Kwsswart This should be included in your config.py file, which you'll load into Flask using app.config.from_object. You can create a .env file which you add to .gitignore and store your SECRET_KEY in there too
Then you can distribute the basic configurations without also distributing your connection credentials
Sorry, you can use python-dotenv to load into your config.py file at runtime. Forgot to mention that part :P
 
12:46 PM
@Kwsswart For the flask setup, you can use something like this. Note that you won't be able to place FLASK_APP into any of those files if you want to run flask from the command line, so you'll have to type that one for each new powershell
 
is there any documentation on how to do this? first flask app I am doing and trying to figure it out
 
I'm reasonably sure it's somewhere in the Mega Tutorial but I can't dig it out specifically right now. It's worth working through the thing once anyway
 
@roganjosh how do you utilize .env with this
 
As I showed in config.py. There's 3 files in that gist. I don't know how you're structuring your app, though, so I'm not sure of the relative file locations
 
this is all separate from application.py
however in the same directory
 
12:51 PM
What are the contents of application.py?
 
and line from dotenv import load_dotenv is this an external library i need to install through pip or is it aiming at the interior module .env
its going to be a web application for docs.cs50.net/ocw/web/projects/1/project1.html
however everytime I restart vscode i have to reload env variables
 
Yes, python-dotenv is an external library that you will need to install with pip. A skim of that link doesn't help me understand the structure of your app.
 
1:27 PM
brief cbg
 
fyi, just in case this really is a Powershell question you use profiles to set up the shell loading options much like bashrc
'ello @JonClements
 
@LinkBerest 'ello... good to see you're around more again... :)
 
@roganjosh Im going to be using flask to make an online app to view and post book reviews using a goodreads api and postgresql
 
Hello, may I interrupt? I got a problem: I can't find my diagramm after using this code:

from numpy import *
from matplotlib.pyplot import *

Multidimensional_Array = zeros( [3, 2] )
imshow(Multidimensional_Array, interpolation = "nearest")

Can anybody tell me where I can find the diagramm?
 
@JonClements yeah, SE seemed to be trying (then again recent events make me wonder if it just another "let's engage enough to pacify people" part of the cycle) - but right now I miss the regulars enough to keep me around :)
 
1:37 PM
@Kwsswart I understand that part. I was asking about the actual structure of your application. Where do you define app? Are you using an application factory pattern? I suspect though that you need to get more familiar with Flask itself before you can answer that so take some I'd recommend going through the Mega Tutorial so you an follow the files I gave in my gist
 
the thanks thing hasn't gone down well to be sure... but they're still trying... but yeah... hanging around with the regulars is the best part for sure :)
 
@Jeroen if no figure window appears, call show(). And give up star imports, that's a bad habit
 
well, thanks, removing the lack of research was big too (I'm an academic - telling people they don't have to research is a hard pill to swallow) - but they rolled back the second thing after feedback so that's at least better than it was
 
import numpy as np
import matplotlib.pyplot as plt

np.zeros(...)
plt.imshow(...)
plt.show()
 
@Jeroen Andras beat me to it: but here's the docs on show examples are on the bottom
 
2:07 PM
Thanks @AndrasDeak and @LinkBerest
 
2:19 PM
How to drop rows based on column if NOT nan
Sorry I meant keep rows if they are nan
df[pd.isnull(df['available_y'])]
 
@LinkBerest I agree, but having to justify a question based on "enough research effort" never felt right. If the question is a valid/non-dupe question, it's worth being on the site, right?
 
2:34 PM
@toonarmycaptain Yet "valid" meant showing enough research effort...
There is a lot of trash on SO that could be "solved" by reading the manual, or dumping an error message into Google.
 
Hello!

This works:
self.player_rest_data_canvas.yview_scroll(2, "units")

But i want to set in in pixels.

This:
self.player_rest_data_canvas.configure(yscrollincrement=self.scrolled_height_temp)

doesn't change anything.
 
@ChrisP literally the only thing that makes sense to me in there is 2 and "units".
 
The available options are: "units" and "page-s"
 
@toonarmycaptain well, this wasn't just SO - that change happened everywhere and on sites like Worldbuilding you can have a question which is bad but not closable (people who ask a question about building a world but haven't done any research)
on the "true" science sites (WB gets a lot of science questions but its not its focus) the above is even worse
 
@roganjosh will do
 
2:42 PM
Hello
 
@ChrisP What's self? What's self.player_rest_data_canvas? What's self.player_rest_data_canvas.yview_scroll? What's self.player_rest_data_canvas.configure? What does, quite literally, any of that code mean or do?
 
Hello
 
@Jeroen What Andras said. "Star" imports are generally a bad idea (although there are some legitimate uses of them). Please see Why is “import *” bad?
 
I'm only saying this one more time: @ChrisP you must give a Minimum, Verifiable Example for people to debug tk code. What you do when building a TK app (in any language) depends so much on the setup of the GUI that it is impossible to debug anything without that MVE
 
question when I run python venv venv I get no such file or directory
 
2:48 PM
These day,I am finding that,but,I didn't get a considerable thing yet.
2
Q: how python variable works?

JanithHow variables work in python? I tried understand it by assigning a value to a variable(a) and checking memory address of it.But,when I changed the value of that variable(a),I got another memory address.what is the reason for that? and that memory address is in the stack area of the memory? and th...

 
@Janith id is a red herring
 
@Janith Did you read the article linked in this comment?
@Janith Also see Other languages have variables; Python has names. The diagrams there are very helpful, IMHO.
 
@PM2Ring Thanks
 
Seriously, it's not helpful to worry about where Python objects are located in RAM, unless you are writing a C extension, or otherwise interfacing from C to Python. Python objects just live somewhere in Magic Object Land. ;) Don't worry about their address. Focus on the name tags you attach to them. It will make your coding life much easier. :)
 
what makes sense is checking existing objects against one another with is
 
3:01 PM
I know it can be hard to break the habit if you're coming to Python from other languages, like C. I was programming for several decades in various lower level languages, including C and a couple of assembler languages, before I started on Python. The freedom of not having to worry about memory addresses is liberating.
 
yeah,It also do cast data type easily not like C.
 
I don't mind people trying to figure out where Python objects are located, if they understand that the answer will require 100 hours of independent research.
 
I think it is in stack area.(functions)
 
yeah, I usually talk about function labels when explaining Python variables to C folk (its not a direct parallel but seems to help)
 
is it possible to allocate heap space in python(dynamic memory allocation)?
 
3:07 PM
@Janith just let go of C
 
I know
 
odds are even your picture of the C stack and heap are wrong
I've seen plenty of posts that explain that most people think of these wrong. And this is python.
 
Python is implementation-agnostic to the point that it has no idea if its hardware even has a heap
 
I think python and c is working differently...
 
@Janith our point exactly
 
3:09 PM
The things you would use dynamic allocation for are largely embedded in Python's built-in types. Linked list? Use a list, set or deque, and freely append to it. Map? Use a dict, and assign key-values as you need.
 
Block of contiguous memory? np.empty :P
 
however,I think people don't talk much about CS related things in python but in C,they do,I don't know why...
 
The low-level memory allocation stuff is all done in the Python interpreter.
 
heap is Python Memory management (Stack is the C extension) I seem to remember - either way its again something you only need in rare cases (like working with pySpark internals or building a C extension or something like that) so shouldn't focus on when learning Python as a new language
 
@MisterMiyagi Totally agree...
 
3:11 PM
@Janith Not really. Data casting in the way that C does it doesn't really exist in Python. But people sometimes use the "cast" terminology when they're being sloppy (or don't know any better). If you do a = 5; s = str(a), you aren't casting a into a string. You are creating a new string object with the appropriate value, and binding that string object to the name s.
 
@PM2Ring you mean the integer to ascii conventions?
 
@Janith area and language usage in that area determine some of that (when I started working everyone talked about CS subjects in C, now it seems to be more Java, and in certain academic circles all Python - it just varies based on backgrounds)
 
Also, don't add \0 to the end of all your strings.
 
yeah
 
Professionally developed Python projects use plenty of CS principles. It might not seem that way if you're just looking at Stack Overflow, since it's overwhelmingly populated by people who have just started learning.
 
3:18 PM
@Janith No. I just mean that str(a) doesn't cast a into a string.
 
@Kevin that actually seems to be a problem in a lot of tags
 
Yes, but I speculate that Python gets it especially bad since its syntax is newbie-friendly (modulo significant whitespace)
 
General CS principles apply to all languages, but you can't simply map the features of one language onto another. You can do that mappung to an extent, depending on how closely related the languages are. But each language has its own rules.
It's like with spoken languages. You can't translate a complex passage from one language into another merely by translating each word, one by one, using a dictionary.
 
@Kevin I'm not sure, some of the Java, JS, and PHP questions make me cringe (still yes, Python is definitely in the top 5 of a list of high percentage of new learners).... that seems like it might be fun to research actually
^ above makes me realize I have a very weird definition of "fun"
 
Welcome to the club :-)
 
3:33 PM
I think that ease of syntax, and Python's abstraction from and inherent handling of things like memory management avoid newbies from having to consider (early on) the concepts that are more front and centre in low level languages because you can't program hello world in them without handling memory or IO streams etc.
 
user13682510
cbg
 
If i run os.system("xdg-open \""+mp3_file+"\"") i must to close vlc or whatever to continue the programm.

I must to put this command in threading?
 
That would probably help, yeah
 
Ok now works.
I am getting one warning:

(totem:226462): Gtk-WARNING **: 18:45:25.214: Drawing a gadget with negative dimensions. Did you forget to allocate a size? (node slider owner GtkScale)


How can i clear it?
 
It might also be worthwhile to investigate whether xdg-open has a programmatic API. Lots of media-playing libraries will provide ways to asynchronously run content, no threading required
 
3:46 PM
@ChrisP gtk throws warnings like that all the time
if you didn't write the gtk code you can probably ignore it
 
Ok, thanks!
 
and totem is a video player which checks out, the bug is probably on their side
 
@Kevin it does not as far as I know (open especially as it just opens a URL with extension handling). Freedesktop has some APIs besides this one though
 
4:21 PM
^ i.e. you can use dbus.SessionBus() to create an instance of Totem but I don't think Totem itself has a Python API (it has a C one so someone certainly could make a library - I just haven't seen one)
 
@LinkBerest Yeah, I thought it was a bit of a long shot. Google tells me that xdg-open basically just forwards the filename to the user's preferred media player of choice. It probably doesn't have a lot of configurable bells and whistles, e.g. "async play".
 
@Kevin It was completed before DBUS was so it was kinda a "we need to test this/this is a neat utility" that's hung around.....cause it is a neat little utility. However, DBUS is the "true" API
 
 
1 hour later…
@MisterMiyagi , might be a dupe
found a target
blargh, third dupe vote doesn't make it a dupe
oh well
 
I've started classifying my commits with labels like feat: or fix:, but I'm not sure how to categorize "made the code compatible with older python versions". I'm leaning towards "fix"?
 
maint?
although that usually refers to the other direction...
 
I like that, actually
 
@AndrasDeak We could reopen it & hammer it.
 
5:57 PM
@PM2Ring meh
@Aran-Fey if you find backwards compatibility valuable enough it could also be "enh"
 
@AndrasDeak Agreed. It's a pretty common error, and probably doesn't need yet another signpost.
 
I vote for "compat:"
 
@Aran-Fey cross-version support is compat for me
 
well, can't argue with that one haha
compat it is
 
@Aran-Fey "legacy: "
(though I use something like compat unless I plan on depreciating it)
 
6:05 PM
compat sounds more... positive
 
6:32 PM
@PM2Ring 'coercing' or 'coercion'. (Whereas 'cast' literally means "telling the compiler/interpreter that the type of the object at the address pointed to by a pointer is type T")
@Aran-Fey perhaps 'retrocompat' rather than 'compat'. (if you're talking about newer features that have been backported to older Python, or reimplementing newer code so it runs on older versions ithout those features? For example, dicts that maintain order, pre-3.6)
 
I'm not sure I understand the difference between the two, but probably the latter
 
6:54 PM
Hey folk, any idea on whether PyCon 2021 is open for proposals/abstract submissions?
 
7:27 PM
Hi there! Just wondering about unittest and parametrised tests — this is something that's apparently possible in pytest, and possible in other languages with which I'm more familiar.

This is the relevant documentation for pytest: https://docs.pytest.org/en/latest/parametrize.html

My use case is I want to run the same test on about a dozen or so input variations, and I am keen to reduce boilerplate and setup.

Is it possible with unittest? Thanks1
just discovered subTest in the docs. i'm guessing it doesn't do setUp and tearDown though.
 
Any reason why you don't use pytest?
 
I use pytest where I can, but this is a legacy project with an existing test suite written with unittest. I guess I could have the conversation about adding another test runner, but I'd rather not at this point.
 
@DarraghEnright I have never been able to find a satisfactory way to parametrize tests with unittest. My current solution is to factor out the test as a private function that takes the parameters and then manually write each test that passes different parameters to the test.
 
@DarraghEnright Pytest can run unittest tests just fine, so it's not really a burden to change anything.. There's an additional pytest-subtests plugin that will run your subtests as if they were individual tests (rather than 20 subtests being one passing test).
 
Ha! Snap... I was literally just starting to do that @Code-Apprentice — yeah, okay, sounds like this is a rational approach.
 
7:40 PM
I recently completed conversion of a project of mine over, most of it done by adding pytest tests for new code, and converting over where changes were made to existing code.
 
class MyTests(TestCase):
    def _test(self, value):
        # do the test using "value"

    def test1(self):
        self._test(1)

    def test2(self):
        self._test(2)
 
@toonarmycaptain — didn't know this. Good to know! Something to mention to the team as a selling point1
Thanks folks!
 
@Code-Apprentice If anyone figures out how to use fixtures as parameters, rather than passing them all to the function and using a dictionary to switch based on a string param or something, I'd love to know about it.
 
@DarraghEnright Let me know if you find a better solution. I program in Django which uses unittest by default. I would love to be able to write real parametrized tests, though.
 
Will do!
 
7:46 PM
Surely it can't be terribly difficult to write a class decorator that dynamically creates a bunch of test functions
 
@Aran-Fey If you were referring to me, maybe it's not, but I haven't tried. I tend to err on the side on not making test code any more complex than it has to be. tl:dr I wouldn't trust myself to not shoot myself in the foot lol
I came up with this:
@pytest.mark.parametrize('desired_fixture', ['fixture_1', 'fixture_2', 'fixture_3'])
def test_something(a_fixture, another_fixture, fixture_the_third, desired_fixture):
    fixtures = {'fixture_1': a_fixture,
                'fixture_2': another_fixture,
                'fixture_3': fixture_the_third, }
    fixture_used = fixtures[desired_fixture]
 
@toonarmycaptain No, that wasn't referring to you. I was just saying that if unittest doesn't give you a parametrize function, you can just write it yourself
 
But I haven't bothered to use it yet because it's kinda crufty, and I would want to use it to test what I'm working on with multiple database backends...and I suspect having several different database backends (sqlite, JSON, PostgreSQL, MySQL, MongoDB) passed to each test might be less than efficient, unless their instantiation is deferred until they're called within the body of the test.
@Aran-Fey Oh, fair enough :)
 
@toonarmycaptain woah, you're going for a mix of SQL and No-SQL backends?
 
No. I've got a working application that I've refactored (it was using JSON files on disk) to have a Database object that can be subclassed as JSONDatabase, SQLiteDatabase, MongoDBDatabse. I'm about to merge this in, then start implementing those as different possible backends.
So...one at a time, but I plan to implement each behind the API of that Database ABC.
 
8:01 PM
SQLAlchemy can be drawn-on for pretty much all the SQL side as-is, but it's pretty epic to try support No-SQL too. Mega project :)
SQLiteDatabase can probably encompass PostgresDatabase and MySQLDatabase without any modification other than setting the SQLA dialect
 
It's just how I decided to put myself to learning db stuff. Might be I'm crazy, but hopefully will be a good learning experience. I've also learned how painful it is to separate concerns after the fact while I've refactored persistence into that Database class, as well as it having to support that 'legacy' JSON files version.
@roganjosh Maybe. I'll probably initially try hand rolled sqlite before using SQLAlchemy. I suspect a base SQLDatabase class might get used given probable similarities.
 
@toonarmycaptain I was looking at PonyORM the other day. It does a nice job of letting you design the tables graphically, and then creates various dialects of table CREATE commands. Also has its own SQLAlchemy-type classes for accessing the tables.
 
@PaulMcG I'll add that to my list. I dunno if I'll get to all of those, I was really thinking of examples for the parametrize example, although that's really my current use case.
 
@toonarmycaptain Thing is, there's mostly just frustrating differences between the SQL dialects, like how you can't use Alembic to DROP columns in SQLite but need to run those as "batch" migrations, or how SQLite doesn't support Boolean type when you try to set constraints. None of this is fun stuff to work through and not particularly enlightening, just facts that there is an existing library with a fix for. Adding No-SQL to support this is probably years of work as a hobby-project
 
8:14 PM
In-browser design of a little project database for recording articles from my Analog magazine collection. Not shown across the top are the buttons for doing the db creates for different dbs
 
I actually have had the tables, primary/foreign keys (is relations the right word?) figured out (I think) since Jan/Feb, but I've been slightly slowed down by being at home with kids while my wife's expecting. Y'know, teaching the young'uns while keeping 'em quiet, and the house in order etc.
 
That's setting Foreign Keys. I'd read "relationships" as ORM stuff
 
@roganjosh Fair enough. That's how the tables 'relate' to eachother in my head.
 
Even if you don't use their ORM, the graphical design tool is helpful (at least for the SQL side).
 
Then again, I use an ORM so maybe it would be a "relationship" in pure-SQL-speak. It's something to join on
 
8:24 PM
A switch by any other name: python.org/dev/peps/pep-0622
 
@roganjosh I don't know (m)any specifics, but I'm aware that they do have differences, different optimisation/indexing options etc
@PaulMcG That's what I thought when I read the post in python-dev, and I only know switch from people talking about python not having one!
 
I think pattern matching is different than switch
 
@toonarmycaptain My initial point was more that you (as I read it) intend to also support the possibility of doing all of those things again with a No-SQL setup. If your intention is to launch a project that supports both backends equally sounds like a perpetual headache. Then again, if DBs are your thing, then it might be an interesting project :)
 
8:45 PM
Ah. Well I know little about noSQL, yet, but apart from maybe having to structure my data differently, it should be possible to provide the same API?
A generic "Here's an object that will work for any projects providing an interface to xyz!@#$ database backends" is NOT what I'm doing.
 
@toonarmycaptain It possibly could have the same API but you'd have to duplicate literally every method based on the backend, and they'd look nothing alike
 
@roganjosh ...That's my plan? I have a JSONDatabase that works right now, that stores each class of students in a json string in a text file. I'm sure the methods for any of the SQL databases will look slightly different.
 
^^ happy to be proven wrong on that one, but I can't see any other way around it. Worse still, you'd have to have different methods for different SQL databases if you don't leverage SQLA, let alone the other options
 
@roganjosh So...I'll learn a thing or two about databases, and their differences? That's the plan :)
Ambitious, dumb..."hey, how ya doing, here's a beer to hold."
 
Hahaha, you'll definitely want that beer back at the end of this adventure :P
 
8:55 PM
My project isn't overly complex. I have classes of students. I produce charts of their scores on a particular assessment or just current grades (no relation between scores or charts is made, just chart-student-score). Each student can have a custom avatar on the chart, aimed at pseudo-anonymity (they're free to tell eachother which one is theirs), rather than using names.
I don't see more effort and duplication as too much of a downside here. If anything, figuring out where the deduplication might take place is a decent exercise, but other than that, it's forcing me to learn about a few different dbs, and SQLAlchemy.
@roganjosh I don't drink beer, but thanks. Guinness, scotch, gin, rum, bourbon, sure ;)
 
@toonarmycaptain I'm not gonna disagree with that because its still just my opinion and I don't wanna dissuade someone learning. I'm not gonna lie, I've got it in the back of my mind to try concoct an example to convince you (I don't know one off-hand without testing). Do you have another db set up other than sqlite? (postgres would be ideal here :P)
The "low-hanging-fruit" is that SQLite doesn't even care about the type definitions you place on columns; shove a datetime into a float column; it won't care. I wanna try to be more sophisticated first :P
 
@roganjosh I don't have either yet, just the JSON I had before reimplemented inside the abstraction I've created. I'm blissfully naiive at this point. I might just end up using SQLA for sqlite/PostgreSQL/MySQL after rolling sqlite by hand.
 
9:17 PM
Hello
How do add border in ttk.Label ?
 
??
 
tkinter doesn't really do borders AFAIK
you can wrap it in a slightly larger Frame with a background color
 
I want it to be ttk not tk.
 
9:24 PM
I don't know tkinter. What am I missing in the difference?
 
I should define it with ttk.style but i don't know how.
 
*rbrb, lol.
 
I have define a general style for all widgets, this style is only only on ttk widgets.
 
@toonarmycaptain rbrb :)
Hmm, TIL that ttk only specifies border padding while tkinter can specify the border width. I have enough trouble with CSS + Bootstrap so I best stay out of this :)
 

« first day (3538 days earlier)      last day (1393 days later) »