0

I'm trying to figure out how to make the objects I create inside a definition appear on the same workspace as my "name == main" area, so I can call it in other definitions. I don't think I can use a simple "return" statement in my def, because my function is designed to create n-number of objects of a particular class.

def book_to_object(subfolders):
    # converts my dictionary of book titles and volumes into individual book objects
    for key, val in subfolders.items():
        title = replace_spaces_with_underscores(key)
        # check to see if book already exists in the registry
        if title in [book.name for book in Book._registry]:
            print("Book already exists")
        else:
            exec(title + " = Book(subfolders ,key, Fpath)")

The whole program below. I'm calling this def from my if __name__ == '__main__': function

print("Done")
#converts my dictionary of book titles and volumes into individual book objects
book_to_object(subfolders)

Originally I had the code in my def in the name=main area of my code but I wanted to reduce the clutter and make it into a definition to give me more flexibility later.

The whole program below.

import os

#get date modified time of a file to determine which file is the newest
def get_date_modified(file):
    return os.path.getmtime(file)

#replace spaces with underscores in a string
def replace_spaces_with_underscores(string):
    aa = string.replace(" ", "_")
    bb= aa.replace('-', '_')
    cc= bb.replace("__", "_")
    title = cc.replace("__", "_")
    return title

# create a list of volumes that have not been exported
def get_unexported_volumes(self):
    unexported_volumes = []
    for volume in self.volumes:
        if volume not in self.last_exported:
            unexported_volumes.append(volume)
    return unexported_volumes

def book_to_object(subfolders):
    # converts my dictionary of book titles and volumes into individual book objects
    for key, val in subfolders.items():
        title = replace_spaces_with_underscores(key)
        # check to see if book already exists in the registry
        if title in [book.name for book in Book._registry]:
            print("Book already exists")
        else:
            exec(title + " = Book(subfolders ,key, Fpath)")

class Book(object):
    #__metaclass__ = IterBook
    _registry = []
    #constructor
    def __init__(self, my_dict, key, Fpath):
        self._registry.append(self)
        self.name = key
        self.volumes = my_dict[key]
        self.Filepath = Fpath + "/" +self.name
        #self.last_exported = self.volumes[0]
        self.last_exported = ""
        self.newest = self.volumes[-1]
        self.last_downloaded = self.volumes[-1]
        self.last_converted = self.volumes[-1]
        self.last_exported_date = get_date_modified(self.Filepath + "/" + self.last_exported)
        self.newest_date = get_date_modified(self.Filepath + "/" + self.newest)
        self.last_downloaded_date = get_date_modified(self.Filepath + "/" + self.last_downloaded)
        self.last_converted_date = get_date_modified(self.Filepath + "/" + self.last_converted)
        self.last_exported_volume = self.last_exported
        self.newest_volume = self.newest
        self.last_downloaded_volume = self.last_downloaded
        self.last_converted_volume = self.last_converted
        self.last_exported_volume_date = self.last_exported_date
        self.newest_volume_date = self.newest_date
        self.last_downloaded_volume_date = self.last_downloaded_date
        self.last_converted_volume_date = self.last_converted_date
        self.last_exported_volume_name = self.last_exported
        self.newest_volume_name = self.newest
        self.unexported_volumes = get_unexported_volumes(self)

if __name__ == '__main__':
    print("Starting")

    # File Paths for Debugging purposes
    Fpath = '~/'
    F_Temp_path = '~/temp'

    #parses directory for book based on folder names
    subfolders = {'Encyclopedia': ['Vol.001', 'Vol.002', 'Vol.003', 'Vol.004', 'Vol.005'], 'Enginnering_Encyclopedia': ['Avionics', 'Civil', 'Electrical', 'Materials', 'Mechanical']}

    print("Done")
    #converts my dictionary of book titles and volumes into individual book objects
    book_to_object(subfolders)

Notes: In case anyone is wondering why I'm using objects instead of keeping everything in dictionaries, I need the flexibility that objects give.

Variables such as, file_paths and subfolders are dynamic and are based on what directory the user gives and what files are in that directory, for the purpose of asking the questions they have been hard coded so someone could copy and paste my code and reproduce the problem in question.

Picky33
  • 11
  • 2
  • This doesn't meet the [\[SO\]: How to create a Minimal, Reproducible Example (reprex (mcve))](https://stackoverflow.com/help/minimal-reproducible-example) requirements. Function is poorly designed, it depends on *Book* being defined. Also it doesn't return anything. – CristiFati Jul 10 '22 at 00:18
  • Oh boy, there's a lot to unpack here, a lot of it ... not so good. Why are you trying to create variables with `exec`, when you already know about dictionaries? It's dangerous, pointless, slow and impossible to maintain. You seem to want to ensure book objects are unique, but why not simply keep them in a dictionary with unique keys, that's what a `dict` is for? You wrote a function, which appears to be setting a class attribute on the `Book` class, why not a class method? Perhaps take a step back and learn what the language already has to offer, before coming up with worse ways to do the same – Grismar Jul 10 '22 at 00:21
  • Also, more to the point of StackOverflow: what is your question? Please provide an example of behaviour you need to change, or show what you need to work, but doesn't. – Grismar Jul 10 '22 at 00:21
  • I have re-written the question, hopefully this clears up any confusion – Picky33 Jul 10 '22 at 01:12
  • @CristiFati I have re-written the question, is this better? – Picky33 Jul 10 '22 at 01:12
  • @Grismar I have re-written the question and provided and example I hope it is clearer now. – Picky33 Jul 10 '22 at 01:13
  • I didn't try it because I don't have the input data (which implies the answer to your question: ***no***). Hopefully you're using *Python**3***, cause the class definition (inheritance) seems copied from some *Python**2*** code. – CristiFati Jul 10 '22 at 01:18
  • There's still no question here, unless you count the sentence "how to make the objects I create inside a definition appear on the same workspace as my "name == main" area, so I can call it in other definitions" - which makes no sense to me. That's maybe not surprising, since none of what you're doing seems to make a lot of sense in Python context, but you've made it clear that you're not interested in doing things the Python way and want to do things your own way. Can you clarify what the actual question here is? Can you give an example of something you'd like to be able to do, but are not? – Grismar Jul 10 '22 at 03:41
  • @Grismar my question is "how to make the objects I create inside a definition appear on the same workspace as my "name == main", maybe I need to reword it a little to say is there away to return all variables inside a definition file, because the code inside a definition can only see global variables, the variables passed to it and the variables created inside of it. once the definition has finished executing all the code the workspace which contained all the variables inside that definition are destroyed . – Picky33 Jul 10 '22 at 04:04
  • @CristiFati I am using python 3 and you are probably right about some code being python2 based, a lot of my programming is trial and error. The variables are Hard Coded into the example above – Picky33 Jul 10 '22 at 04:05
  • Are you asking "how do I create a global variable from a function?" because in that case, the answer is simply `global var_name` and `var_name = 'some value'`. Refer to here https://stackoverflow.com/questions/10588317/python-function-global-variables - that's about changing a global variable, but for defining one the same applies. You would do well to use the language others use to describe what you're after. "the definition has finished", you're talking about functions. "The name == main area", your talking about the script, or global namespace. – Grismar Jul 10 '22 at 05:29

0 Answers0