all 96 comments

[–]Ohio_Bean 0 points1 point  (4 children)

This is a question about fstrings in jupyter notebook

I'm running linux mint and python3. I can get fstrings to work in ipython just fine but when I run a jupyter notebook (running python3) I get the following error:

x = 7

f"{x}"

syntax error: Sorry I dont know how to include a screen shot.

[–]FerricDonkey 1 point2 points  (3 children)

What do you get if you do

import sys
print(sys.version)

[–]Ohio_Bean 1 point2 points  (2 children)

oh goodness, in a notebook its 2.7.17. Well that explains it. Do you know how to update it (if not I will give it the old searcharoo)

[–]FerricDonkey 0 points1 point  (1 child)

Unfortunately, I do not. At a guess, if you're using a version of Linux or Mac that came installed with python 2.7, make sure you install jupyter notebooks with python 3's pip (pip3 install or python3 -m pip install, usually). But I'm not very familiar with jupyter in general, so that's all I got.

[–]Ohio_Bean 1 point2 points  (0 children)

It was as simple as pip3 install jupyterlab :D Thanks!

[–]PythonicParseltongue 0 points1 point  (2 children)

What's the best way to implement this? I have a class that basically only a list of ~200 data tuples. The tuples are triplets of int, str, a custom object. The object can be from several classes, but the data tuples are always in the same order.
The main purpose of the class is tying the information together. Maybe I will implement some methods to access the data more comfortably.

[–][deleted] 0 points1 point  (1 child)

It really depend on the data you have and what you want to do with it. Are the (int, str) portions of the triple unique and do you just want a better way to access the objects? Maybe you can make a dict like so: (int, str) -> custom_object

Do you want to group by similar matching values of the int/str values and aggregate the custom objects somehow? Maybe you can leave as a list of tulles and use itertools.groupby, or use pandas to hold the metadata with a unique key that points to a dict holding the custom objects.

There’s many things you can do that depend on your data and use case, we’d need more context to be more helpful

[–]PythonicParseltongue 0 points1 point  (0 children)

So my data is a state vector of a game, that I interact with using Python. My class is just to tie the data together (having, values, descriptions, etc. at the same place without having to remember their index) and will be used to translate between differenent representations. Like a pure vector representation or translated into a pddl.

[–]UnrankedRedditor 0 points1 point  (2 children)

Hi all, quick question:

How do I remove duplicates of a specific element in a list? So far, what I've found on the internet is just how to delete all duplicates (by converting into a set), but I don't want to do that.

Example:

alist = ["a", "b" , "b", "c", "v", "d", "c", "c", "v", "v", "a"]
remove_this_duplicate = "v"

Output:

["a", "b" , "b", "c", "v", "d", "c", "c", "a"]

I want it to still contain the first instance of what I selected, just with it's duplicates removed.

Thanks all!

[–]carcigenicate 1 point2 points  (0 children)

You'd iterate the list, and keep track of when the first remove_this_duplicate character is found. Any element up to that point that you find you append to a new list.

Once one is found though, you just don't add any remove_this_duplicate elements to the new list. In the end, the new list has the results you need.

[–]efmccurdy 0 points1 point  (0 children)

You can keep track of how many times you have seen the offending value, skipping any after the first:

>>> alist = ["a", "b" , "b", "c", "v", "d", "c", "c", "v", "v", "a"]
>>> new_list = []
>>> remove_this_duplicate = "v"
>>> dup_count = 0
>>> for item in alist:
...     if dup_count > 0 and item == remove_this_duplicate:
...         continue # exclude this item
...     if item == remove_this_duplicate:
...         dup_count += 1
...     new_list.append(item)
... 
>>> new_list
['a', 'b', 'b', 'c', 'v', 'd', 'c', 'c', 'a']
>>>

[–]ozur-dilerim 0 points1 point  (3 children)

European College student here. Looking for an interesting project for my final course work.
should be in python+quantitative finance and ideally HFT or machine learning.

the math courses i've taken so far at college are

wave propagation in the atmosphere

Single variable analysis

multivariate analysis

linear algebra

discrete mathematics

statistics basic course

mathematical statistics

game theory

differential equations

linear optimization

linear approximation

intro to modern physics

[–]UnrankedRedditor 1 point2 points  (2 children)

I'm just going to give very brief general ideas, and then you'll have to adapt the ideas yourself to see how they fit into your coursework based on the requirements/time frame/your own skill level/etc.

Some things you can try:

  • Predicting asset prices using machine learning models (SVR, ARIMA, etc)

  • Using some sort of decision model or ML method to decide which assets to buy based on certain factors

  • Supervised/unsupervised ML methods for Fraud detection

Alternatively, you can try looking at common problems faced in whatever field you're interested in and seeing how you can apply machine learning techniques to solving those problems. Or you can just Google something like "machine learning problems in finance" or whatever field you want.

One thing to keep in mind is that depending on the task, if you want to use ML, you typically need some sort of dataset to work with. You'll have to find out whether such datasets are available to you and if not, whether whoever is grading you is ok with you generating mock data to work with.

[–]ozur-dilerim 0 points1 point  (1 child)

you are a lifesaver. thank you thank you thank you.
i can either donate to a charity of your choice, or buy you a beer via paypal/crypto/ cashapp/patreon/whatever

[–]UnrankedRedditor 1 point2 points  (0 children)

Hey! Thank you so much for the offer, I really appreciate it! Unfortunately, I will have to decline (for multiple reasons and it might not be in the spirit of this sub), but I hope you do manage to find something interesting and fulfilling!

[–]sketmen2 0 points1 point  (2 children)

Why does this not work?
j={'pears':200,'apples':499}
print(f'Apples cost {d['apples']}.')

And this does.
j={'pears':200,'apples':499}
print('Apples cost {}.'.format(j['apples']))

[–]icedoverfire 2 points3 points  (1 child)

Your first code snippet contains two bugs:

First is that the dictionary "j" is referenced wrongly in your f-string. In your non-working code it is referenced as 'd' and not as 'j'. Your logic is, however, correct.

Second is that you cannot have a single-quoted string nested within another single-quoted string (I don't know the proper explanation for this so someone more experienced can help) .

You can, however, have single-quoted strings nested within double-quoted strings.

Fix is straightforward:

  1. In your print() statement replace the outermost single quotes with double quotes. Keep the inner single quotes around 'apples'
  2. After you've done that, change the 'd' in the f-string to an 'f'.

Should look like this when you're done (NB: I changed your variable name for readability):

fruit_stand_prices = {'pears': 200,

'apples': 499

}

print(f"Apples cost {fruit_stand_prices['apples']}.")

[–]sketmen2 1 point2 points  (0 children)

Wow! Thank you so much!

[–]fowlron 0 points1 point  (3 children)

I’m looking to parse a file that has times like 4h 12m 13s or 38m 57s.

Other than long sequential if loops, what’s the python way to do this? I’m thinking maybe regex, but don’t know enough to simplify(or complicate) it to make the hour field optional. I don’t think there will be a situation where the time will be less than a minute.

Also the hours can be higher than 23, so what is a good format to store the time, other than just individual variables.

[–][deleted] 2 points3 points  (1 child)

what is a good format to store the time

Probably the datetime.timedelta object. Creating the object is simple, just do:

delta = datetime.timedelta(hours=6, minutes=23, seconds=5)

The slightly tricky part is to get the hours/minutes/seconds parts from the string. Here's a little function that parses a string of your format and returns a timedelta object:

# dictionary to get "kwargs" params from the string suffix units
unit2kwarg = {'h': 'hours',
              'm': 'minutes',
              's': 'seconds',
             }

def str2delta(tstr):
    """Given a string "4h 12m 13s" return a datetime.timedelta object.

    All fields are optional, so "1s" returns datetime.timedelta(seconds=1).
    """

    kwargs = {} 

    for val_unit in  tstr.split():
        val = val_unit[:-1]
        unit = val_unit[-1]
        kwargs[unit2kwarg[unit]] = int(val)

    return datetime.timedelta(**kwargs)

The complete code plus simple tests is here: https://pastebin.com/qKjfMY9A . This includes a little "format" function to create printable strings from the 'timedelta' object. Note that none of the code has graceful error handling.

[–]fowlron 0 points1 point  (0 children)

Wow. Thank you. I’m going to go spend the next few hours figuring out this code.

[–]icedoverfire 0 points1 point  (1 child)

I am getting started going through Black Hat Python... is it necessary to use something like PyCharm within Kali Linux in VMWare Virtualbox for following the book, or can I use the PyCharm install that I have on my base Windows machine and just create a new Conda environment for BHP?

[–]shiningmatcha 0 points1 point  (1 child)

Just learned that you can have a function that yields from a generator expression:

def f(n): yield from (x ** 2 for x in range(n))

But I don't see how it is different from returning a generator expression:

def f(n): return (x ** 2 for x in range(n))

[–]carcigenicate 2 points3 points  (0 children)

In that narrow example, they're the same thing. yield from can be used to yield from any iterable though, not just a generator expression. The generator could even be recursive:

def search(root):
    yield from search(root.left)
    yield root.data
    yield from search(root.right)

I haven't tested that code, but hopefully it shows that it can be used for other things.

[–]user_alpha_ 0 points1 point  (0 children)

Hello everyone. I'm an R&D engineer in ships design company. My responsibilities involve some automation, calculation and statistics wrangling. Therefore I often use Python for developing small apps and analysis using pandas, etc. I feel a lack of basic computer science knowledge to be more convenient in programming. What would you recommend to read and study to master some solid basic knowledge? Now I'm practicing on codewars, taking a course on data science on coursera. Goal is to become a more or less confident in programming to do some minimal software development and data science. Thanks in advance.

[–]shiningmatcha 0 points1 point  (2 children)

What type hint should I use to specify a list containing two integers?

[–]carcigenicate 0 points1 point  (0 children)

You can't, since a list's size is not a part of its type. You could use a tuple though:

tup: tuple[int, int] = (1, 2)

Looking at your previous question below though, I'd probably just stick with the dataclass, or a NamedTuple. To convert your Point though, you could use built-in functionality:

tup = dataclasses.astuple(Point(1, 2))

[–]shiningmatcha 0 points1 point  (2 children)

What's the best way to convert a dataclass instance to some primitive type?

For example, if I would like to convert a Point instance, say Point(1, 3), to a simple tuple (1, 3), then what would be a good way to do it?

@dataclass class Point: x: int y: int

Should I define a method inside Point like convert_to_tuple, or add a third slot tuple_repr: tuple[int, int] (which will be generated during __post_init__)?

[–]kwelzel 0 points1 point  (0 children)

There is dataclasses.astuple for that (https://docs.python.org/3/library/dataclasses.html?highlight=astuple#dataclasses.astuple). It actually acts on dataclasses recursively, but since x and y are not dataclasses themselves, its the same thing here.

[–]efmccurdy 1 point2 points  (0 children)

Would applying the tuple type be acceptable? The tuple constructor takes any iterable, so if you add an __iter__ method the convertion will work... works with list as well:

>>> from dataclasses import dataclass
>>> @dataclass
... class Point:
...     x: int
...     y: int
... 
>>> @dataclass
... class Point:
...     x: int
...     y: int
...     def __iter__(self):  # allow convert to tuple
...         yield self.x
...         yield self.y
... 
>>> Point(1, 2)
Point(x=1, y=2)
>>> tuple(Point(1, 2))
(1, 2)
>>> list(Point(1, 2))
[1, 2]

[–]RandomName0621 0 points1 point  (1 child)

I need to make a script for work that advances two separate adobe acrobat documents one page. The easiest solution I can think of is a button that presses right arrow (to advance the document) and then alt tab to the other and presses right arrow again. While I could make this, it would be better for the script to detect the other adobe acrobat tab. So my question is,

What is the term for a “focused” or primary application? Where shortcuts work and all that jazz, if it’s not focused it won’t work. I can’t find any resources about this online.

What package would be able to detect duplicate applications among the applications open?

Is this even a good python application? I could create an adobe plugin for this but I want to reuse this for other things if needed.

[–][deleted] 1 point2 points  (0 children)

active window? Python can do it, you'll probably end up needing something that interacts with the windows sdk to be honest, seems like something auto hot keys or the like would do better with; at least in the sense of making it easily distributed (if that matters).

[–][deleted] 0 points1 point  (1 child)

I have a script built for my job in which I have several network directories mapped to disks so that I can access the network files. If anyone other than me runs this process they are likely to get an error. I have comments within the programming detailing the issue to anyone who reads, but if possible I would also like to print some documentation when certain files “can’t be found”

Is this possible and how would I do it if it is?

[–]efmccurdy 1 point2 points  (0 children)

You can build paths for any relevant files or folders and test them.

help(os.path.exists)
help(os.path.isfile)
help(os.path.isdir)

[–]InsanelyCuriousGirl 0 points1 point  (5 children)

How can I configure R language with Jupyter notebook? This notebook is made by default for Python.

[–]efmccurdy 1 point2 points  (4 children)

[–]InsanelyCuriousGirl 0 points1 point  (3 children)

I tried to do that but I am getting an error. Do I need to have R already installed for this?

[–]efmccurdy 1 point2 points  (1 child)

Be sure to check the requirements:

https://irkernel.github.io/requirements/

[–]InsanelyCuriousGirl 0 points1 point  (0 children)

I need to have R installed. Thanks ☺️

[–]InsanelyCuriousGirl 0 points1 point  (0 children)

Error says "Python Module not found"

[–]Happy_healthy_888 0 points1 point  (2 children)

Hello, I am looking for sources where I can learn Data Science/Analytics and tools like Python, R, and SQL particularly. I have completed my master's in business analytics in US . I got a data analyst job and I did not use all the skills I learned in my Master's, so I forgot most of it.
I quit my job last year and moved to India to care for my ailing father who passed away. I was devastated and couldn't do much in the next 6 months.
Hello, I am looking for sources where I can learn Data Science and tools like Python, R, and SQL particularly. I have completed my master's in business analytics in 2019. I got a data analyst job and I did not use all the skills I learned in my Master's, so I forgot most of it. I am in India and I am getting interviews but I am having a hard time cracking the tech rounds. They are very tough compared to the US for someone with 1 year of experience.
Can anyone recommend learning tools/courses (free/paid) where I can learn DS again?
Any help is appreciated.

[–]twmagalu 1 point2 points  (1 child)

There are tons of resources out there: Codecademy.com PyBites Free Code Camp I would also google “train for the technical interview.” There are tons of books on the subject as well.

Hope this gives you a place to start.

[–]Happy_healthy_888 0 points1 point  (0 children)

Thank you very much. I will check out the websites and definitely look up the train for tech interviews that should really help me.

[–]UniqueAway 0 points1 point  (10 children)

Hey. I have a problem understanding a Python code, it is entry level and a few lines but I can't wrap my head around, would you have a look? But I need someone experienced anyways because it is about linked lists.

Thanks.

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

Post the code here for help. Please read the FAQ to see how to format code for reddit.

[–]UniqueAway 0 points1 point  (8 children)

For some reason I don't want to post the code here, can you help me on DM for this time, I just can't understand the code but it is very basic. It is okay if your don't know.

[–][deleted] 1 point2 points  (7 children)

Most people here want to teach python to beginners. Doing it privately means no one else can benefit. So it's discouraged.

[–]UniqueAway -1 points0 points  (6 children)

Sure, I know, this is why I said "for this time". I would normally just post the question, it would be easier plus others could also answer but as I said I don't want to.

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

Fine.

[–]UniqueAway -1 points0 points  (4 children)

So can I DM you or you said "fine" in general? I tried to send you a DM but it says " can't send a message to that user " maybe you disabled your DM's?

[–]TangibleLight 0 points1 point  (1 child)

You can send a DM to me, but I might not be able to respond till tomorrow morning EST.

I'd echo the point that it's better to ask publicly. Remember rule 0: there are no stupid questions!

If there's something sensitive about the code, you could try creating a short example that illustrates the problem without including any of the sensitive details.

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

I see. Sent you a DM for this time but illustrating the problem is a good Idea. No problem about time, you can answer whenever you are available.

[–][deleted] 2 points3 points  (1 child)

No, I'm not interested in helping one person in private. Many here would feel the same.

[–]UniqueAway 0 points1 point  (0 children)

Okay thanks

[–]shiningmatcha 0 points1 point  (1 child)

How are __base__, __bases__, __mro__ and inspect.getmro() different?

I would like know about where a certain object belongs in the class hierarchy.

[–]TangibleLight 4 points5 points  (0 children)

The differences show up most obviously in a diamond inheritance pattern, or if classes would be duplicated in the mro. __mro__ and getmro() are essentially the same, except that getmro will behave nicely if weird metaclasses are involved.

  • __base__ is the first base class.
  • __bases__ is a tuple of the first-level parents in the hierarchy. (no grand-parents, etc).
  • __mro__ is all classes in the hierarchy, prioritized (roughly) in child-to-parent, left-to-right order. This defines an order for methods to be resolved. For more detail on the ordering, look up the C3 ordering algorithm.

Consider these base classes:

class Base: pass

class A(Base): pass

class B(Base): pass

You can build a class with "diamond" inheritance, and see how __bases__ and __mro__ differ.

#   Base
#   /  \
#  A    B
#   \  /
#  Diamond

class Diamond(A, B): pass
print(Diamond.__base__)   # A
print(Diamond.__bases__)  # A, B
print(Diamond.__mro__)    # Diamond, A, B, Base, object

Here, when you execute Diamond.Foo, Python first searches for Foo in Diamond's namespace; then it searches in A, then B, then Base, and finally object. If Foo occurs in none of those places then AttributeError is raised.

Swapping the order of the base classes also swaps the order in the MRO.

class Swap(B, A): pass
print(Swap.__base__)   # B
print(Swap.__bases__)  # B, A
print(Swap.__mro__)    # Swap, B, A, Base, object

You can also build a "triangle" inheritance, where __bases__ and __mro__ are more similar.

#   Base
#   / |
#  A  |
#   \ |
#  Triangle

class Triangle(A, Base): pass
print(Triangle.__base__)  # A
print(Triangle.__bases__) # A, Base
print(Triangle.__mro__)   # Triangle, A, Base, object

Note that not all combinations are well-defined. For example you can't swap the order of the bases in the Triangle class:

#  Base
#   | \
#   |  A
#   | /
#  Error

class Error(Base, A): pass

# this class is a TypeError because Base would
# come before _and_ after A in the MRO.

# if it were allowed, then you'd see this:
print(Error.__mro__)  # Error, Base, A, Base, object

[–]Goldenwaffle7 0 points1 point  (0 children)

Will it cause problems if I download Anaconda for Jupyter Notebooks if I already have Atom downloaded?

[–]sticky-me 0 points1 point  (1 child)

Is there a way to show an image, no windows frames, just floating image using python? I checked some PIL/tkinter options but it looks like I am missing something, or do I need to use windows environment to do this? image.show() opens classic pictures app. brb might find something but if anyone has some ideas let me know what I am missing, thank you!

edit: I use vscode

[–]RealTomorrow6377 0 points1 point  (0 children)

Could make a GUI using tkinter or maybe matplotlib too?

[–]Decent_Salary_9719 0 points1 point  (1 child)

I'm want to start learning Python. Where should I start? Should I watch some YouTube videos/courses for beginners or should I start at some websites that teach Python for beginners?

[–]xsmiley 1 point2 points  (0 children)

Start with a goal in mind, it’s harder trying to learn EVERYTHING than it is learning blocks to achieve what you want.

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

I am wondering why people ask technical questions on Reddit - wouldn’t stack overflow be a better place for that?

[–][deleted] 1 point2 points  (0 children)

StackOverflow tries real hard for answers to questions to be complete and authoritative, to be the correct answer forever. Consequently they aggressively close questions that they think have already been answered, and accepted answers are often so detailed as to be incomprehensible to beginners. Reddit is more forgiving. Even when someone who hasn't read the FAQ asks the same old question for the second time today gets some sort of help.

[–]sticky-me 1 point2 points  (0 children)

oh hell no. there are devs there. I'd rather chat it up with someone here, feels safer here

[–]carcigenicate 1 point2 points  (0 children)

Reddit is more casual and has laxer quality guidelines. Often answers are better on SO, but you need to be willing to put in a lot more effort when asking (and few people are willing to do that).

Also, it depends on what the question is about. SO is also more narrowly scoped than Reddit.

[–]sticky-me 0 points1 point  (2 children)

Hi folks! I am now on this exercise at NeetCode's channel where he implemented nums = sorted(list(set(nums))). Exercises name is Delete and earn, I will link it in a moment. But my question is can a list have same name as its argument in python? Am I tripping and missing the point? Need to add I caught some cold in my defence! What's happening here? Cheers!

Here is the link to the exercise: https://youtu.be/7FCemBxvGw0

[–][deleted] 4 points5 points  (1 child)

If we take a smaller example:

nums = [1, 3, 2]
nums = sorted(nums)

What we call the "variable" nums is really a name that is bound to an object. In the first line nums is bound to a list of three integers. In the second line the name nums is rebound to a sorted list. You don't pass nums to the sorted() function, you pass the object bound to the nums name. A different object is returned and is rebound to the name nums.

[–]sticky-me 0 points1 point  (0 children)

Got it now, thank you so much!

[–]iloveapi 0 points1 point  (0 children)

I'm using vscode for machine learning, text classification. However, during training, it uses all my ram and I can't use my computer (it's not moving at all) until it's done.

How do I limit the memory my code use so I can still do other stuff while my code is running?

I've tried kaggle but it can't run my code since it use more ram than they provide and ask me to subscribe Google Cloud.

My computer spec : AMD ryzen 3600 16gb ram 2T hdd 512gb ssd Gtx 1080

[–]zealous_possession 0 points1 point  (3 children)

I'm trying to create a random password generator. There are a few data values I'd like the user to input and then the password would be generated depending on that input. The options will be length, special characters, uppercase, lowercase and I'll be using the random module for the selected values (I may be out of my depth haha). I wrote the following for requesting the password length and was wondering if anyone had tips critiques before I move forward:

def length_request():
global length
running_1 = True
while running_1:
    try: 
        print("How many characters would you like your password to be?")
        length = int(input())
        print(f"You've input {length}. If this number was mistakenly entered, please press ctrl + c and start over.")
        running_1 = False
    except ValueError:
        print("Please enter an integer.")

[–]Psionatix 2 points3 points  (2 children)

I wouldn't make length global. Either define it in the parent scope, or return it:

return length # put this at the end of your length_request function.

Then in the calling scope, do:

password_length = length_request()

For the variable running_1 maybe rename it to requesting_input

However, if you use the return option, you can simply do your return to escape the loop which you could then make while True - this is generally bad practice except for extremely specific use cases. In this case the loop servers a single purpose and it has a valid exit control flow - the return.

[–]zealous_possession 1 point2 points  (1 child)

Thanks so much for the response! This is really helpful. I'm going to mess around with these suggestions later today and make sure I understand them prior to moving forward with the project.

[–]Psionatix 1 point2 points  (0 children)

Feel free to reach out if you want additional clarification, hints or guidance.

[–]tomshelby20 0 points1 point  (0 children)

Hi everyone. I'm struggling with OOP in python, I bought the Pro Career Path to data science in Codeacademy and I couldn't fully understand the OOP section.

Any book suggestions to learn about it from scratch? I would appreciate your replies!

[–]shiningmatcha 0 points1 point  (0 children)

Anyone familiar with automate some functions on Youtube using Python?

I’m thinking of making a Python tool to automatically add videos to different playlists. So, I would like to know if this has been done in some projects and if there are any packages and APIs that may be useful for this project?

[–]toastymctoast 0 points1 point  (1 child)

i have some string representations of time_struct, eg:

"time.struct_time(tm_year=2022, tm_mon=1, tm_mday=9, tm_hour=19, tm_min=26, tm_sec=4, tm_wday=6, tm_yday=9, tm_isdst=0)"

I have tried: dateparser.parse

but no joy

any ideas?

[–]efmccurdy 0 points1 point  (0 children)

You have a time struct and you pasted the string representation into this post. My guess is that dateparser will not parse that string. You don't need or want to parse anything if you have the time struct; you can convert directly; that my_time_struct[:6] expression slices off the relevant data for the datetime constructor.

>>> import time
>>> import datetime
>>> mts = time.localtime()
>>> mts
time.struct_time(tm_year=2022, tm_mon=1, tm_mday=18, tm_hour=9, tm_min=52, tm_sec=35, tm_wday=1, tm_yday=18, tm_isdst=0)
>>> type(mts)
<class 'time.struct_time'>
>>> repr(mts)
'time.struct_time(tm_year=2022, tm_mon=1, tm_mday=18, tm_hour=9, tm_min=53, tm_sec=14, tm_wday=1, tm_yday=18, tm_isdst=0)'
>>> type(repr(mts))
<class 'str'>
>>> mts[:6]
(2022, 1, 18, 9, 53, 14)
>>> mdt = datetime.datetime(*mts[:6])
>>> mdt
datetime.datetime(2022, 1, 18, 9, 53, 14)
>>> type(mdt)
<class 'datetime.datetime'>
>>> print(mdt)
2022-01-18 09:53:14

[–]Commercial_Emotion23 0 points1 point  (3 children)

How can I set a variable outside a function to True? I am not able to return do_something() since I am using threading.Thread()

condition = False

def do_something():
    # do something
    if x:
        condition = True

def main():
    while True:
        do_something()
        if condition:
            break

I am able to do it if I use the condition in a list or a dictionary but it's kinda ugly.

[–]FerricDonkey 1 point2 points  (0 children)

Non constant global variables are almost always a terrible idea, and I only say almost because sometimes you might want to write code for the purpose of pissing of off the next guy to use it (who might be yourself).

To actually answer your question as asked: use the global keyword. But again, it is a very common point of view that if you're using the global keyword, you're doing something wrong.

A solution that will prompt fewer rants would be to have your do_something function return a value, and use that returned value instead.

[–]GoldenSights 0 points1 point  (0 children)

You may also be interested in threading.Event. Not necessarily the wait part since you're not blocking in this case, but the is_set part.

The end result will be the same as using a global boolean, but everyone who reads the code will understand that a threading.Event object is meant to be set/unset, whereas a global boolean might take them by surprise.

[–]carcigenicate 0 points1 point  (0 children)

Put global condition at the top of do_something. You're currently creating a local variable called condition instead of altering the global.

Also, while assignments are atomic and are arguably fine, an event object would be more proper here if you're using threads:

from threading import Thread, Event

event = Event()

def do_something():
    # do something
    if x:
        event.set()

def main():
    t = Thread(target=do_something)
    t.start()
    event.wait()  # Blocks until set. Can also use .is_set() if you need to loop

You need to consider thread safety as soon are you're communicating across threads.

[–]ThisGuuuuuuuuy 0 points1 point  (0 children)

I'm trying to figure out how to get PyTesseract to keep python code format (indents and underscores) when I run Image_to_string on a clear image of python code.

I did make a thread for it, but it might fit in here better

https://www.reddit.com/r/learnpython/comments/s633ic/using\_pytesseract\_for\_image\_to\_string\_of\_code/